如何使用 HTTParty gem 在 Rails5 中与外部搜索 API 交互?

How do I interact with an external search API in Rails5 using the HTTParty gem?

如何在 Rails 中创建一个应用程序,让我输入搜索参数,然后将这些参数传递给外部 API 以执行搜索,然后在我的应用程序中显示这些结果.我正在尝试使用 HTTParty 来实现这一点,但我有点迷路了。我试过在 app/services 中创建一个 class 方法并在我的控制器中访问它,然后在我的视图中调用实例变量。目前它正在抛出路由错误 uninitialized constant ResultsController::Api。非常感谢您的帮助。

services/Api.rb

class Api
  include HTTParty
  base_uri "search.example.com"
  attr_accessor :name

  def initialize(name)
    self.name = name
  end

  def self.find(name)
    response = get("/results&q=#{name}")
    self.new(response["name"])
  end

results_controller.rb

class ResultsController < ApplicationController
  include Api

  def index
    @results = Api.find('test')
  end
end

路线:

Rails.application.routes.draw do
  resources :results
  root 'results#index'
end

您几乎是对的,只是需要在此处进行一些更改。首先,将 Api.rb 重命名为 api.rb - 按照惯例,所有文件都应以较低的 snake_case

命名
class Api
  include HTTParty
  base_uri "http://search.spoonflower.com/searchv2"

  def find(name)
    self.class.get("/designs", query: { q: name }).parsed_response
  end
end

class ResultsController < ApplicationController    
  def index
    # here you get some json structure that you can display in the view
    @results = Api.new.find('test')['results']
  end
end