API and Object Interaction Extravaganza in Ruby
APIs are exciting. I am serious. Stop laughing at me.
They have the ability to turn a sandboxed coding project into an application that interacts with the world outside of your computer and local files. There is a lot of information coming your way so let me list the sections in advance:
- Thinking About Object Interaction & Program-to-Program Communication.
- Connection the Dots
- The Client/Server Model.
- Use It Or Lose It
- Ruby API Step 1: Understanding
- Ruby API Step 2: Searching & Selecting
- Ruby API Step 3: Get Access
- Ruby API Step 4: Endpoints
- Ruby API Step 5: Use an API
- Ruby API Step 6: Make it Dynamic
- Conclusion
Thought Experiment Time
Imagine a bunch of kids in a sandbox, in the middle of a field. In the distance, the kids can see people, buildings, cars, etc. They are generally aware of what these things are but have no way of interacting with them. One day, three of the children notice a bakery. With their eyes transfixed on the storefront, the children watch a typical interaction unfold: a customer enters, the cashier takes the customer’s order, a baker brings out a loaf of bread, the cashier requests payment, the customer gives payment, then takes the loaf and leaves.
The three children immediately start to play make-believe bakery and each of them assumes one of the three roles in the bakery (customer, cashier, baker). When it comes time for the customer to pay, the cashier says “that’ll be one million dollars.” An argument ensues between the cashier and the customer over the true price of the loaf.
The argument goes on and on due to the fact the children have no concept of how much the bread actually costs. Tired of all the bickering, the baker leaves her imaginary bakery and asks one of the older kids to walk over to the real bakery that inspired the game in the first place and get the true price of a loaf of bread. The older kid does just that and returns a few minutes later with the information. Thereby putting an end to the cashier-customer quarrel and allowing imaginary business to resume.
Connecting The Dots
The make-believe game described can be viewed as a Bakery application with four classes: Customer, Cashier, Baker, and OlderKid. The Customer, Cashier, and Baker serve as the conspicuous workings of our Bakery. However, without OlderKid, the Bakery is doomed to forever float in make-believe.
Imagine the kids continue their bakery into adulthood and eventually decide to start an online shop called Bread.com that allows online customers to order bread from bakeries across the city. Bread.com will do this by connecting with various bakeries’ websites,(e.g. Citybakery.com) and getting the type and price of each of the bread loaves they offer. All of the sudden, the importance of the OlderKid is much more apparent. OlderKid would be the determining factor in the viability of the the online bakery, since it would be OlderKid’s role to provide accurate information from all the bakeries around the city.
The Client/Server Model
The basic interaction between OlderKid and a bakery’s website is similar to one we use every time we visit a website. This interaction is called the Client/Server Model. The Client is your Browser, the Server is the machine hosting the website you are trying to view. The interaction can be viewed as a conversation between the Client and the Server. Think of clicking a link as initiating a dialogue:
You click a link, telling your browser to visit a website.
Your browser responds: “Great, I’ll get right on that”
Your browser says to the server hosting Google.com: “Hi! Can you send me the relevant files to display Google.com?”
The Server responds: “Sure thing! Here it is”
Your browser says to you: “I received the raw code and will now present it in format that is easy for humans like yourself to understand”
This entire conversation can happen in less than a second and if you look closely at the bottom of your browser when a website is loading, you can even catch the updates: “waiting for Google.com” “processing request.” This request and response interaction allows the server to control the flow of information and creates one gateway through which all clients can make requests. Essentially, the server makes it easy for any browser to contact and request info.
Comparing the client/server model to the relationship between Bread.com and Citybakery.com, we can see similarities. However, Bread.com is not a web browser that will just display Citybakery.com. Bread.com is trying to be the one-stop-shop for all of your bakery needs, pulling and presenting accurate data from bakeries around the city for its users. Luckily for Bread.com, we can build a mechanism for each of its partner bakeries that will allow OlderKid to get up-to-date information automatically, whenever he wants. That mechanism is an API.
Use It Or Lose It
At this point we are going to say goodbye to Bread.com and hello to “Use It Or Lose It,” an app that my classmate, Grant Yoshitsu, and I made for our first project while attending Flatiron School (you can read more about Use It Or Lose It, from conception to execution by clicking here). The primary function of Use It Or Lose It(or “UIOLI” for short) is to provide recipes to users based on their selected pantry items. While conceptualizing UIOLI, we knew that an API would be required to execute this function.
Using an API in Your Application
Step One
The first step for Grant and I to make this happen, was to understand what the hell an API is.
API stands for Application Program Interface and is a set of rules that allow one program or system to communicate with another. The communication is accomplished through a GET request. Remember, the dialogue in the client/service model? When the client(your browser) sends a message to the server asking for more information, it is sending an HTTP GET Request. An API is utilized with its own GET request that can be used to integrate either data or functionality from one entity into another.
Examples of using an API for functionality include allowing visitors to your website the ability to create an account with their Facebook credentials or including a small Google Maps widget on your website. For UIOLI, we needed to find an API that could provide specific data which our application would then be able to manipulate and present to our users.
Step Two
Once we sort of understood what we were dealing with, it was on to searching for and selecting an API. As this was my first time using an API, I ran a Google search for “easy to use food APIs.” I quickly found that there are thousands of options at your fingertips, but many of them are paid services so I changed the search to “easy to use food API free” to narrow the field. This new search provided a few options to compare. In order to do this, you need to look at an API’s documentation.
When you go to a particular API website, look for the “Doc” or “Documentation” link. This is where you will find an explanation from the API provider on what types of data you have access to and how you can get it. The API I found was from a company called “Spoontacular.” Below you will see the documentation for the particular endpoint (URL for a specific searchable dataset) called “Search Recipes by Ingredients.”
After looking through the examples of GET requests on the documentation page, I decided Spoontacular would be perfect for UIOLI.
Step Three
It is time to get access to the API you selected. This is arguably the most straightforward step, as all you need to do is sign-up. You will either be signing up directly with the API company or with an API database, such as RapidAPI, that gives you access to thousands of APIs through one sign-up. After signing up, you will be given a unique API Key to access that company’s data.
Step Four
Next we needed to understand the endpoint, which is just the URL that we send our GET requests to. In other words, an endpoint is the thing you enter to get to the thing. Let’s look at endpoints in the context of an HTTP GET request to Google’s server for information about puppies.
GET Request for Google homepage
Endpoint: http://www.google.com
GET Request for Google for Information about puppies
Endpoint: https://www.google.com/search?q=puppies
GET Request for Google for Images of puppies
Endpoint: https://www.google.com/search?q=puppies&tbm=isch
GET Request for Google for Videos of puppies
Endpoint: https://www.google.com/search?q=puppies&tbm=vid
Notice above, we include all information about our puppy search within the URL. An API Endpoint functions in a similar way. The main difference is that while you can visit Google.com without any queries attached, you cannot do this with an API endpoint. The purpose of the API is to send a query.
Let’s build the URL that we will use to access the API and as we do so, look at how different queries are delineated in the URL:
“?” marks the beginning of the queries
“&” separates subsequent query types
“+” separates search items within one parameter type
Endpoint for getting recipes based on selected ingredients.
https://api.spoonacular.com/recipes/findByIngredients
There are no queries attached to the above URL so the response would be an error. The one query that is always required is the API key so we will add that first
https://api.spoonacular.com/recipes/findByIngredients?apiKey=123abc123abc
Wonderful! Now we have the authorization to access the data ready to send to the server with our GET request. There could be an API for “Returning all recipes” in which case no other queries would be required. In regards to this Spoontacular endpoint, the documentation does not allow a “return all” so at least one ingredient query is required
https://api.spoonacular.com/recipes/findByIngredients?apiKey=123abc123abc&ingredients=onion
Now we are searching for all recipes that have an onion as an ingredient. Maybe we should add one more for good measure:
https://api.spoonacular.com/recipes/findByIngredients?apiKey=123abc123abc&ingredients=onion+garlic
Spoontacular also allows you to set the number of search results you want to receive with the “number” parameter. For UIOLI, we only wanted 10 results per search:
https://api.spoonacular.com/recipes/findByIngredients?apiKey=123abc123abc&ingredients=onion+garlice&number=10
Right now our URL includes three search parameters (apiKey, ingredients, and number) and we are ready to go!