# 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:

```ruby
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:

```ruby
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.

\
\
\ <br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.promptjoy.com/api/api-usage/ruby-on-rails.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
