Lesson Weekend

Let's say we want to add a search function to our literary quotes API. For example, users should be able to pass in Jane Austen as a parameter and our API should return only literary quotes by Jane Austen. How could we do this?

Structuring the API call itself is simple. In Postman, we'll want to pass in a GET request that looks like this:

http://localhost:3000/quotes?name=austen

Then, in the index route of quotes_controller.rb, we can grab the name parameter just as we do with a form submission:

quotes_controller.rb
def index
  name = params[:name]
  binding.pry
  @quotes = Quote.search(name)
  json_response(@quotes)
end

I threw in a binding.pry so we can check the value of name when we make the API call. Here's a cool thing: binding.pry works exactly the same with an API call as it does when we manually load an HTML page. The application will freeze (and the API call will be suspended) until we exit pry.

Here's what shows up in pry:

Rails Process Graphic

We grab the name parameter and then call a search method on the Quote class. Try writing a search function yourself and adding it to the quote.rb model. This is a great opportunity to practice writing scopes.

One more thing: you do not need strong parameters to pass in parameters with GET routes; strong parameters are only needed when using a method such as POST or PUT.

A user can technically pass any parameter into an API call, but we'll only grab parameters that fit the specifications of our API. This is another reason why excellent documentation and clear error handling are essential for an API. When a user fills out a form, it's obvious which fields need to be filled out. However, it's not so obvious with an API call.

Try adding options for passing parameters into your API calls. You can use parameters to make computations, add queries, and narrow down searches, among other things.

Lesson 9 of 19
Last updated more than 3 months ago.