Ruby on Rails

In a Rails application, you might want to wrap the API call into a service object for better organization and reusability. Here's how you can do it:

First, create a new file under app/services directory (you might need to create this directory if it doesn't exist yet), named book_search_service.rb and put the following code into it:

class BookSearchService
  require 'net/http'
  require 'uri'
  require 'json'

  def self.search(query)
    uri = URI.parse("https://api.promptjoy.com/api/mVMCpq")
    request = Net::HTTP::Post.new(uri)
    request["Content-Type"] = "application/json"
    request["X-Api-Key"] = ENV['PROMPTJOY_API_KEY']
    request.body = JSON.dump({
      "query" => query
    })

    req_options = {
      use_ssl: uri.scheme == "https",
    }

    response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
      http.request(request)
    end

    if response.code == '200'
      return JSON.parse(response.body)
    else
      raise "HTTP Request Failed with code #{response.code}"
    end
  end
end

Then, in your controller, you can use this service to search for a book as follows:

class BooksController < ApplicationController
  def search
    query = params[:query]
    @search_results = BookSearchService.search(query)
    render json: @search_results
  end
end

In this example, the search term is expected to be passed as a parameter named query in the request to the search action of BooksController. The search results are then returned as a JSON response.

This example uses Net::HTTP, which is part of Ruby's standard library. If you're more comfortable with another HTTP library like httparty or rest-client, feel free to use that instead.

Remember to handle exceptions and errors as needed in your actual application code.

Note: In this example, the API key is retrieved from environment variables for security reasons. Ensure that you've set the PROMPTJOY_API_KEY environment variable in your environment where this code will be executed.

Last updated