How To Query A Basic API In Ruby (RubyShorts)

How To Query A Basic API In Ruby (RubyShorts) - Webdesign Antwerpen


Querying API's

API stands for application programming interface. Which is basically a fancy way of saying that the creators of the web application you're trying to query have given you partial/limited access to their database. 

This allows you to send get, post, patch, put or delete requests (whatever is allowed) with your code in order to retrieve or alter data. (Note that not every application is publicly accessible and most even require you to send some type of "key/string" with the request to authenticate yourself). The most basic one I could found was the pokemon api! 

Follow the link to try it out;

Most api endpoints return a JSON response but could also serve CSV, XLS, XML or other types of data back. JSON is just the most-widely used. So - let's get started!

require "open-uri" # Allows us to send GET requests and receive the response
require "json" # Allows us to parse the reponse into a JSON object/hash

So now we can do

response = open("").read
=> {"forms":[{"url":"http:\/\/\/api\/v2\/pokemon-form\/65\/","name":"alakazam"}],"abilities":[{"slot":3,"is_hidden":true,"ability":{"url":"http:\/\/\/api\/v2\/ability\/98\/","name":"magic-guard"}},{"slot":2,"is_hidden":false,"ability":{"url":"http:\/\/\/api\/v2\/ability\/39\/","name":"inner-focus"}},{"slot":1,"is_hidden":false,"ability"...}

So now we have a JSON string we can parse into a JSON object;

json = JSON.parse(response)
=> {"forms"=>
  [{"url"=>"", "name"=>"alakazam"}],
     {"url"=>"", "name"=>"magic-guard"}},
     {"url"=>"", "name"=>"inner-focus"}},
     {"url"=>"", "name"=>"synchronize"}}],
  [{"stat"=>{"url"=>"", "name"=>"speed"},
     {"url"=>"", "name"=>"special-defense"},

=> Hash

And now we can basically treat it like any other ruby object, let's say I wanted to retrieve all moves that alakazam can learn as he levels up, I can do;

json["moves"].collect {|move| move["move"]["name"]}
=> ["mega-punch",
 "psychic", # THIS is probably the strongest move of alakazam. ALWAYS use your pp-ups on this!

Pretty cool huh!