Comment on page

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'
uri = URI.parse("")
request =
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|
if response.code == '200'
return JSON.parse(response.body)
raise "HTTP Request Failed with code #{response.code}"
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 =
render json: @search_results
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 modified 5mo ago