DEV Community

Cover image for Selecting Hashes from an API
Kimberly Kohel-Hayes
Kimberly Kohel-Hayes

Posted on • Updated on • Originally published at kak79.github.io

Selecting Hashes from an API

Selecting hashes from an API can seem like a very complicated process, so let's take it one step at a time. We will be storing everything in variables for ease of access. The definition to a variable can be found here.
The first thing we are going to do is set our API equal to a variable named response. Then we are going to put in a pry (see more about pry here) and look at our available hash.

Alt Text
We want to select a key from response that has multiple keys as it's value. If we look closely, 'page'=>1,'per_page'=>1 so they each have individual returns and 'photos'=>[{ which means not only does it have an array, it has an array of hashes.
We are going to save 'photos' into the variable photos_array like this and run the pry again to select our next key.

Alt Text
Alt Text
We are going to pick three. 'photographer', 'photographer_url', and 'src'=>'original'
So using our binding.pry we gradually develop these three lines of code:

Alt Text
This code will work. But it isn't very DRY code. Don't Repeat Yourself! We are going to refactor this code next.
Because we want to iterate over three things we are going to use the .each method, naming our variable photographer_hash and setting up the block something like this:

Alt Text

Now we have a new Photographer object that iterates through my API and returns all of the values. But it could still be better. Instead of Photographer.new...., we are going to set up a new variable called info_hash. Set it equal to:

Alt Text

The reasons behind the locally defined keys pic_taker, pic_taker_url, and orig_url have more to do with OOP and classes than APIs and refactoring so will not be gone into here. Just understand that they were defined in another class. The last thing to do here is to put Photographer.new back in with its new argument of info_hash with the resulting API looking like this:

Alt Text

All of the code examples in this article and their associated files can be found here.

Top comments (0)