Lesson Weekend

Imagine that we work at a dev agency and we just got a new customer: a little indie bookstore in Portland that's ready to build an online presence. They'll be selling books online and they'd like their site to have a list of the latest New York Times bestsellers at the top of the page.

It's time to make some calls to NYT's API, which has excellent documentation. You will need to go to the link above and follow the instructions to get your own API key.

Here's the call in Postman:


It's a GET request to a /lists endpoint with a header for the api-key. Note that the api_key has been crossed out and that you'll need to add your own key. Let's make the call using a Ruby gem.

Using HTTParty

There are several excellent gems that make API calls easy, including RestClient and HTTParty. We'll cover HTTParty in this lesson, but you're welcome to try out Rest Client as well. Both of these gems can be used in Rails, Sinatra and Ruby projects.

Before we start, there's one very important thing to note. Unlike with JavaScript, we don't need to worry about CORS when we make API calls from a Ruby application. This is because our applications aren't based in the browser.

Start by adding gem 'httparty' to your Gemfile and then bundle. For now, we'll make the API call in the Rails console. In the next lesson, we'll discuss where we should put the code for API calls. If you want to test this call yourself, make sure to get your own API key from the New York Times.

Here's the call:


That's it. We tell HTTParty to execute a GET request to the chosen endpoint and we'll include our own API key in the query string.

The response will already be formatted as a JSON object, so we won't need to do any additional parsing but note that you will if using Rest Client. In that case, you would want to check out the docs on Ruby's JSON module.

Note that JSON objects are surrounded by {}. JSON arrays are surrounded by [].

We can use square bracket syntax to home in further on specific parts of the response. For example, we can grab the title of the current #1 bestseller: JSON.parse(response)["results"]["books"][0]["title"]. This will find the ["title"] at position 0 of ["books"] (which is a JSON array) which is in turn nested inside ["results"]. If we wanted to return the titles of all the books on the list, we’d need to loop through ["books"].

For POST requests, you’ll have to pass in a payload. A payload is the body of an HTTP POST or PUT request. Passing in a payload can be as simple as passing in parameters like this:

HTTParty.post('http://website.com/resource', {school: 'Epicodus', class: 'Rails'}

This would POST the payload (the school and class params) to the specified URL. You could also use the .execute method, which is preferable if you need to pass more involved options into the call. Different APIs will require different parameters; for instance, you may need to pass in user, password and payload, to name a few.

Storing Sensitive Information in Environmental Variables

There’s an issue with our API call. We haven’t put the call inside a Rails project yet, but once we do, we’ll need to keep any sensitive information private. We can do this by using environmental variables, just as we did with sensitive information when we made API calls in JavaScript.

For this particular call, we’ll need to store the api_key in an environmental variable:

response = HTTParty.get('https://api.nytimes.com/svc/books/v3/lists/combined-print-and-e-book-fiction.json?api-key=' + ENV["NYT_API_KEY"])

Now, we need to set the variable outside of our application. Let’s store them in a .env file in our project directory:


We also need to make sure that Git doesn't track our .env file by adding .env to the end of the .gitignore file.

Now we need a way to load the variables from our .env file. There's a nice gem for that called dotenv:

group :development, :test do
  gem 'dotenv-rails'
  gem 'rspec-rails'

Make sure that you store all sensitive information in environmental variables!

Sample RestClient call


Use square bracket notation: JSON.parse(response)["results"]["books"][0]["title"]

Store sensitive variables in .env. Use a gem like dotenv and make sure to add the .env file to .gitignore.


Lesson 4 of 27
Last updated July 14, 2022