Making a Basic API Call

For this example we’re going to make a call to the Open Notify APIs from Space. These provide 3 methods to explore

  • the current location of the ISS;
  • overhead pass predicitons for the ISS; and
  • the current number of people in space

You can take a look at the API docs here: http://open-notify.org/Open-Notify-API/

API Details

We’ll use the ISS Current location API. For this we’ll make a call to the API endpoint. From the docs we know:

API Method URL: http://api.open-notify.org/iss-now.json

Example response: 
{
  "message": "success", 
  "timestamp": UNIX_TIME_STAMP, 
  "iss_position": {
    "latitude": CURRENT_LATITUDE, 
    "longitude": CURRENT_LONGITUDE
  }
}

The data payload has a timestamp and an iss_position object with the latitude and longitude.

Working with APIs in Ruby.

There’s one gem we can use to make HTTP REST calls with Ruby: HTTParty. Take a look at the guide for it.

Installing HTTParty

Add it to your gemfile and bundle install then require at the top of your app.rb

gem 'httparty'

Now let’s make a request to our API

response = HTTParty.get('http://api.open-notify.org/iss-now.json' )
print response.json

Yes… it’s that easy…

(Note: This example can be found in full in ‘iss-now.rb’)

Now, let’s get more complicated…

We’ve made a GET request and parsed a JSON object to print the lat and lon. But this is the most basic of API calls: it didn’t need any parameters and the output was simple.

Let’s try the predicted pass times method and experiment with this API method. From the documentation we see it needs two required parameters

  • Latitude - The latitude of the place to predict passes
  • Longitude - The longitude of the place to predict passes

Let’s try this out.


response = HTTParty.get("http://api.open-notify.org/iss-pass.json")
print response.code
print response.message

And this gives us

400
{
  "message": "failure", 
  "reason": "Latitude must be specified"
}

We get a 400 status code, which indicates a bad request; and we’re told that we need to add the two missing parameters

We’ll make a request using the coordinates of Pittsburgh (40.4406° N, 79.9959° W), and see what response we get.

parameters = { query: { lat: 40.440, lon: -79.9959 } }
r = requests.get("http://api.open-notify.org/iss-pass.json", parameters)
print r.status_code
print r.text

Your turn.

Two exercises

  1. Modify the ISS Pass times example to loop over 3 different cities and make calls for each of them.

  2. Create a program that calls the Open Notify People in Space API method and prints out a formatted list of the names of people currently in space to the console.

×

Subscribe

The latest tutorials sent straight to your inbox.