What Is An API

What is an API?

The internet is home to numerous web applications that have created vast data. Much of this data has been made available through the use of APIs. Let’s say you want to add stock market data to your website. There’s an API for that. If you want to add the weather, there’s an API. If you want to add information about the best-reviewed restaurants in your town, there’s an API. APIs are a fundamental piece of how many web applications work. But what exactly is an API, and how do you use one? In this tutorial, we’ll look at the fundamentals of APIs and how they work. We’ll break down APIs in simple terms and demonstrate how you can get started working with APIs to incorporate data into a website quickly and easily.

Application Programming Interface

API stands for Application Programming Interface. While it may not be obvious what that means initially, it’s a relatively straightforward concept. One way that may help to understand APIs is to think of them as a sub-shop. Let’s say you’re in the mood for an Italian Submarine Sandwich. You could make it from scratch, but you’d have to go to the store, buy all the ingredients, and make it yourself. That takes too much time and effort. The other option is to go to the sub-shop. The food is excellent there, and all the work has already been done for you. You order from a menu that lists all the available sandwiches and organizes them into different categories. Once you decide, you tell the server what you’d like. I’ll get the Italian Sub. They take your order to the kitchen, and the food is brought to you, ready to eat. It’s excellent, you get the food you want, and you don’t have to make it yourself. You don’t even have to know how they made it. You just had to know how to order it, and now, you can enjoy delicious food without doing any work. This is an excellent analogy to think about how APIs work. With an API, you also want to get something. Although it’s not food, it’s data. There are all kinds of companies out there that provide data through the use of their APIs. Data on TV shows, weather, finance, outer space, sports, you name it. Like a menu in a restaurant, companies provide documentation that explains what data’s available and how to ask for and get that data. Then, like a sub-shop server, you request that data from the API, and it gets it and brings it back for you to use as you like. Again, you don’t have to create the data like your food at a restaurant. You don’t have to create a tool to access it. And you don’t have to understand how it’s made. You order it, and then you get to enjoy it.

Request Response Lifecycle

To understand APIs, it’s essential to have a basic understanding of the request and response cycle. With the request, you ask for something. And with the response, you get something back. The request and response cycle involves communication between your web browser and a server somewhere.

You and your web browser are often referred to as the client. The request you typically make is a GET request. You request to get data from the server. Making GET requests to get data from an API is very common. Now, GET is just one of the things we can ask of the server in our request. Several request options use the HTTP Protocol, often referred to as verbs.

HTTP GET

GET: GET is an HTTP method for requesting data from the server. Requests using the HTTP GET method should only fetch data, cannot enclose data in the body of a GET message, and should not have any other effect on data on the server.

HTTP POST

POST: The POST request method requests that a web server accept the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or submitting a completed web form.

HTTP PUT

PUT: The HTTP PUT request method is used to create a new resource or overwrite a representation of the target resource that the client knows. Calling this method once is similar to calling it multiple times successively, as it has the same effect.

HTTP PATCH

PATCH: The HTTP PATCH request method applies partial modifications to a resource. PATCH is somewhat analogous to the “update” concept found in CRUD (HTTP is generally different from CRUD, and the two should not be confused). A PATCH request is a set of instructions on modifying a resource.

HTTP DELETE

DELETE: The HTTP DELETE request method deletes the specified resource.

After we make a GET request to the server, the server will respond to us. If we’ve been good and made a request correctly, that response will include all the data we hoped to get from the API.

JavaScript Object Notation

So our goal with making a Get Request is to get some data back as a response. So, what data will we get? What we should ask is, what format will that data come in? There are two main data formats you’ll see. XML and JSON. XML used to be the most popular format, but now JSON dominates the web. And that’s the data format we’ll be working with. JSON stands for JavaScript Object Notation. And this is one of the reasons it’s so handy to use. JSON formats the data like an object in JavaScript, so it can be easily used in our web projects, like any other JavaScript object. If you’re not familiar with working with objects, don’t worry. We’ll do a basic overview a little later, providing you with all you need to work with it for our purposes. So let’s look at the syntax for JSON. The real key with JSON is that it comprises key-value pairs. The key is like a property and then its corresponding value.

{
   "name":"Thomas",
   "food":"Italian",
   "color":"Blue"
}

So here you see name is a key, and its value is Thomas. Programmers must write keys inside of quotes and be double quotes. The value must also be inside double quotes if it’s a string. Keys are separated from values with a colon. And key-value pairs are separated by commas. And all the key-value pairs are contained within curly brackets. In addition to the name key, there is a food key with a value of Italian and a color key with a value of Blue. JSON was meant to be a simple key-value store and does that well.

How To Parse Data

When data is sent in the response, it’s sent as a string or text. To work with the data, we want to convert it into a JavaScript object. This process of converting the string to an object is often called parsing. We use the Java Script method JSON.parse to complete this task. As an argument, the method will take the response that we get from the API. So this method will take the response and convert it from a string to an object we can use like any other JavaScript object. You’ll sometimes see this as an array, but it’s still considered an object, just multiple objects contained in an array, and you can access each with standard array index syntax. Some of the API data we’ll work with in this tutorial will be an array of objects. Parsing the data makes it more readable and looks like object formatting instead of a string. But then, practically, these are completely different data types, and we can interact with them differently. One of the things I like to do is see under the hood a bit of understanding better what’s going on. And one way I think this is helpful is to get confirmation about the data type. There’s a handy Java Script operator we can use called typeof. And it’ll tell us what data type we’re working with. We need to tell the typeof operator what data we’re curious about.

var request = new XMLHttpRequest();

request.open("GET", "https://dog.ceo/api/breed/havanese/images/random");

request.onload = function () {
  var response = request.response;
  console.log(response);
  console.log(`the response type is `, typeof response);
  // the response type is string
  var jsonData = JSON.parse(response);
  console.log(jsonData);
  console.log(`JSON.parse() turns a sting into a JS`, typeof jsonData);
  // JSON.parse() turns a sting into a JS object
};

request.send();

Let’s look at an example of our data in its raw form, as a string and then as an object after it’s been parsed. The initial response from the API request we made above comes in string format. Here is the string.

{“message”:”https:\/\/images.dog.ceo\/breeds\/havanese\/00100trPORTRAIT_00100_BURST20191 126134713895_COVER.jpg”,”status”:”success”}

It looks like JSON, but you can see that every special character uses an escape sequence with a backslash. Those backslashes tell us this is still in native string form. This is where the JSON.parse() function comes into play. The code sample above makes use of the JSON.parse() function like so:

jsonData = JSON.parse(response);

After JSON.parse() has completed processing, the data is in a different format. It is now an object within the JavaScript language.

{
   "message":"https://images.dog.ceo/breeds/havanese/00100trPORTRAIT_00100_BURST20191126134713895_COVER.jpg",
   "status":"success"
}

To open this up in our browser, we’ll double-click on the index in the HTML file. To see this in the browser console, we’ll use the command + option + j. And then, we can see everything we printed out to the console. So first, if we scroll up, we’ll see the raw data that was returned, and we can see that it’s a string, or at least it looks like a string, and then as we scroll down, we see that in fact, the type of data we have is a string. Right after that, we have our parse data which comes to us as an array, and as we click to expand this, we see that it has the object formatting. And as we scroll down, we see that the data type we’re working with is an object. So this can be something helpful that you might want to do when you’re initially working with data and converting between different data types to have a clear idea of what’s happening.

This code would work nicely to make a similar API request using JQuery.

$.ajax({
  url: "https://dog.ceo/api/breed/havanese/images/random",
  success: function (response) {
    console.log(response);
  },
});

JavaScript now has a built-in fetch() function programmers can use to request data from a server. The request can be of any API that returns the data in JSON or XML. The fetch() method requires one parameter, the URL to request, and returns a promise. Fetch defaults to GET requests, but you can use all other types of requests, change the headers, and send data. fetch() is built on the Promise object, which significantly streamlines the code, particularly if used in conjunction with async/await. The code below makes the same GET request to the API URL as the examples seen above.

fetch("https://dog.ceo/api/breed/havanese/images/random")
  .then(function (response) {
    return response.json();
  })
  .then(function (respData) {
    console.log(respData);
  });

How To Handle JSON

Working with JSON means working with objects. Object-oriented programming dominates most of the programming for the web, and it’s a vast topic. We’re just barely going to touch on it now. We’ll cover just enough so that you can work with API in JSON. What is an object? Well, often, the answer you’ll get is everything. Everything in programming is an object. It helps to think about objects in programming, like objects in real life. Real objects have properties associated with them. Take a car. A car has properties related to it, like its make, model, year, weight, color, et cetera. Objects also have actions associated with them. Again, with a car, it has actions associated with it, like accelerating, stopping, turning, honking, et cetera. Here’s an example of what the code would look like if we turned a real-life car object into a javascript car object. Here we can see the car object has properties like make, model, and year. And it has a honk action, which is a function. When a function is attached to an object, it’s usually referred to as a method. We use dot notation to access an object’s properties, actions, or methods in code. With our car object, we see how we would use dot notation to get the object’s properties and methods. For example, car.make would return “Tesla.”

var car = {
  make: "Tesla",
  model: "Model 3",
  year: 2023,
  acclerate: function () {
    alert("Wow that's fast!");
  },
  driver: { name: "Thomas", license: "FL" },
};
console.log(car.make);
console.log(car.driver.name);

And this dot notation is what we will focus on. To work with APIs in JSON data, it’s essential to understand dot notation to access an object’s properties and methods. Sometimes the data we’re working with can get a little more confusing to read and understand. This often happens when we start getting objects within objects. Layers of objects can be tricky to work with. Here, we’ve added a driver object within the car object. It has its properties of name and license. Fortunately, there’s a pretty simple way to access this data. Every time you need to access an object within an object, you add another dot. Think of it like a file path. You keep adding dots to drill down and get the object with the property you want. So to access the name property, we use car.driver.name.

Python Requests JSON

We can call the same API using code written in Python instead of JavaScript. Python offers easy ways to ingest JSON data, just like JavaScript does. In the following Python code, the first thing we do is import the requests module. The requests module allows you to send HTTP requests using Python. The HTTP request returns a Response Object with all the response data. By typing requests.get() and passing in the URL of the API endpoint, the program makes an HTTP GET request and stores the response in the response variable. After that, we print out both the string version of the response and the JSON version of the response, just like we did in the JavaScript example earlier.

import requests

response = requests.get('https://dog.ceo/api/breed/havanese/images/random')

print(response.text)
# {"message":"https:\/\/images.dog.ceo\/breeds\/havanese\/n02085936_1003.jpg","status":"success"}

print(response.json())
# {'message': 'https://images.dog.ceo/breeds/havanese/n02085936_1003.jpg', 'status': 'success'}