1 comment
Great post!
Could you do another one going further on how to consume apis from websites that require authentication (through devise)?
APIs are great because they let you interact with other applications, but they can be a bit intimidating if you never used one before.
In this post I will show you how to get started using your favorite APIs with Ruby.
To use an API you will need some form of HTTP client. I like RestClient
because it’s easy to use.
Example: Random Chuck Norris joke
1 2 3 4 5 6 7 8 9 |
require 'rest-client' require 'json' url = 'http://api.icndb.com/jokes/random' response = RestClient.get(url) json = JSON.parse(response) puts json.fetch("value").fetch("joke") |
This code sends an HTTP ‘GET’ request to the server using RestClient.get(url)
, then it receives a json string as a response which needs to be parsed by JSON.parse(response)
. The parsed json is just a regular Ruby hash that we can use to get the data we want, in this case the joke.
The documentation for this API is available here.
Api responses can be pretty complex, and it can be hard to read the resulting json to find what you need. Fortunately, the json library has the jj
method to pretty-print the output.
In the example above you can do this:
1 2 3 4 |
# rest of the code ... json = JSON.parse(response) jj json |
And this is what you get:
1 2 3 4 5 6 7 8 9 |
{ "type": "success", "value": { "id": 311, "joke": "When Chuck Norris sends in his taxes, he sends blank forms and includes only a picture of himself, crouched and ready to attack. Chuck Norris has not had to pay taxes, ever.", "categories": [ ] } } |
As you can see the json structure is more clear now. You can even go a bit further than this with the awesome_print
gem, which will add some syntax coloring to the output and even better formatting than jj
.
If you want to use an API from a popular site like Github or Reddit there are gems you can use to make your life a lot easier.
Example: Using the Octokit gem to get the top 10 Ruby projects on github.
1 2 3 4 5 6 7 8 9 10 11 |
require 'octokit' # Query the API repos = Octokit.search_repos "language:ruby", sort: "stars", order: "desc", per_page: 10 # Print the names p repos.items.map(&:name) # Get the next 10 repos = Octokit.search_repos "language:ruby", sort: "stars", order: "desc", per_page: 10, page: 2 |
The gem’s documentation should have all the possible API calls you can do with it. Also you can use pry’s ls
command to help you explore the available options.
APIs are fun! Now open your editor, use some APIs and create something nice 🙂
Great post!
Could you do another one going further on how to consume apis from websites that require authentication (through devise)?