Search code examples
ruby-on-railsrubyapihttparty

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


How can I create an app in Rails that will let me input search parameters, which are then passed to an external API to perform the search, and then display those results in my app. I'm trying to use HTTParty to achieve this but I'm a bit lost. I've tried creating a class method in app/services and accessing it in my controller, and then calling the instance variable in my view. At the moment it's throwing a Routing Error uninitialized constant ResultsController::Api. Would be super grateful for some help.

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

Routes:

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

Solution

  • You're almost right, just need some changes here. At first, rename Api.rb to api.rb - by convention, all files should be named in lower 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