Cats and APIs

Have you ever wondered what an API is and how it works?

Just something for fun I whipped up. This showcases how easy it is to work with an API (Application Programming Interface). The idea is that an application should be able to "share" and "receive" content with other applications.

For example, Instagram ought to be able to post to Facebook for you. An API is simply the process an application asks you to use.

See the Pen at on CodePen.

The link to the cat API documentation is here:

You can see that I can use the code api/images/get?format=xml&results_per_page=20 which ought to allow me to:

This is a very commonly formatted request. It consists of the type of request and the parameters of the request.

The type of request is GET and the parameters are format=xml and results_per_page=20

There are two types of requests: GET and POST. The main differences are that GET requests can be bookmarked and publically seen in the address bar, while a POST request cannot. It is a general rule that GET requests be used for frequently accessed searches and POST requests be reserved for less-used and more secure events like submitting forms or passwords.

You'll notice the parameters have two values on either side of the equals operator. The first word is considered the key, while the second word is considered the value. The API documentaiton lets you know the various keys which can be used and you get to supply a valid value. 

This is how applications talk to each other!

But, since you are paying good money to host your application, you wouldn't want anyone to abuse your API. The solution to this problem is requiring developers to sign up and receive a secret API key. This key is sent as a parameter to most APIs to track and restrain usage and even fairly charge users if they go over a certain limit of requests.

In the code example, you can probably spot the GET request. All the other JavaScript code is simply using the send() method from the built-in JavaScript object called XHRHttpRequest which allows us to ask another server something. The if else jazz is just to help us debug if there is an issue. Know though, that you don't need to use JavaScript to call an API with a GET request. Did you know that you use GET requests every day? Whenever you type an address into your browser, you make a GET request to places like Google, Amazon, and Facebook. Start watching your address bar more closely and you'll see what I mean!