Adding Postgres and ActiveRecord
Getting started - adding dependencies to your project
Guides, tutorials and labs to accompany CMU's Programming for Online Prototypes (49-714).
Everything you need to know about building microservices for the web with Ruby and Sinatra.
For this example we’re going to make a call to the Open Notify APIs from Space. These provide 3 methods to explore
You can take a look at the API docs here: http://open-notify.org/Open-Notify-API/
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.
There’s one gem we can use to make HTTP REST calls with Ruby: HTTParty. Take a look at the guide for it.
Add it to your gemfile and bundle install
then require at the top of your app.rb
gem 'httparty'
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’)
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 passesLongitude
- The longitude of the place to predict passesLet’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
Two exercises
Modify the ISS Pass times example to loop over 3 different cities and make calls for each of them.
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.