A Beginner's Guide to APIs: How to Integrate and Use Them

Do you want to pull in weather data for your users? Get them the latest sports scores for your app? Want to make a site that tells your user a random joke?

You could go about writing all those jokes yourself or copying and pasting them into a file for your site to read from. Or you could just start using API integration and give your code superpowers to automate the whole process.

When you learn how to use an API, you're able to use services that would otherwise take you a long time to code yourself. You can add a robust search to your site with Algolia's API or a complete eCommerce experience with a SaaS Snipcart.

In this article, we'll go through:

  • What’s an API?

  • How to do an API integration?

  • How to make a simple app with an API?

  • How to troubleshoot API issues?

  • Best API integrations to get started with

  • No-Code API integration platforms

I'm excited to get you up and running with APIs integration! Before making a demo app with an API, let’s learn...

What’s an API?

API stands for Application Programming Interface, so we'll start by learning what an interface is.

What’s an interface?

Every device we use has some kind of interface. Your microwave has numbers and a start button on it, while a light switch has an even more straightforward interface.

We use these interfaces to get the device to do what we want. We don't need to understand the underlying circuitry and science to heat a bean burrito. We only need to use the interface that's been exposed to us.

Compare the internal workings of a car engine to what we interface with.

The inner complexity is abstracted away, leaving the user with the most straightforward interface possible.

APIs provide a layer of abstraction for the user. Abstraction hides everything but relevant to the user, making it simple to use. Abstraction is a concept you'll often see in programming, so it's helpful to understand it well.

What’s the "application programming" in API

Now that we know what the Interface portion means, the Application Programming bit is easier to understand.

An API is how applications talk to each other.

All software that you can interact with through code has some form of an API, so you'll see the term pop up in many places.

When web developers talk about "hitting an API," they usually mean a web service that lets you send requests and receive data in return. We'll touch on these soon.

Whenever I'm wondering, "How do I get this code to do what I want?" I searched for the API documentation related to that code.

You might have looked at the documentation on JavaScript libraries like Lodash to figure out how you need to format your code. The documentation teaches you how to use the API for that library.

How do web APIs work?

Your web browser has plenty of APIs built into it that we can use! These are called Web APIs. Chrome, Firefox, Safari, etc., have them built-in to use them to add features to our sites.

Some APIs let you play audio files, let your app understand user speech, respond to video game controllers, and lots more! When you listen for a click or a keyboard press in JavaScript, you're using the Event web API to do it.

We'll mainly look at HTTP web APIs for the rest of this article since web developers are most often referring to them when talking about API.

These are APIs that sit between your code and some data sources or functionality on a server that you'd like to access. They most often use the REST API architectural style to conform to certain criteria when making HTTP requests.

The API generally does two things:

  1. For one, it sets rules for interacting with it.

The "rules" are the API saying, "if you structure your request like this, I'll send you data that's structured like this." If you don't structure your request in a way the API is expecting, it won't know what you want, and you'll get an error in response.

  1. The API also handles data transfer between the server and the code making the request. The API is a program that acts as a middleman between the web app and the server and database.

Once it receives a valid request, it will run a function (or multiple functions). This is the complexity that the API is abstracting for the user. Depending on what you ask for, it might return an image, some data, or just let you know that it successfully received your request.

Let's touch on some concepts that you should understand when working with HTTP APIs.

Endpoints

APIs provide you with an endpoint or a specific URL where the data or functions you want are exposed. For Unsplash's source API, you access images through their endpoint at [<https://source.unsplash.com/>](<https://source.unsplash.com/>), adding your query parameters after the end slash.

In a later section, we'll look at some API documentation that outlines this agreement.

Authentication

Some APIs require you to sign up for an account or obtain a unique key to access their information. It might be to secure data, prevent abuse of the service, or because they want to charge a fee for the data.

If you're changing data on your database through an API, you need authentication. You don't want to give anyone else the ability to edit or delete your files!

With authentication, you pass the API a secret key that identifies a specific user or application request. The server can then determine if you're able to access the data or not.

If an API requires authentication, the API's documentation will explain how that works.

HTTP Verbs

With each HTTP request created, there is always an 'HTTP Verb' that goes along with it. The most commons are GET, POST, PUT, and DELETE.

When websites request data from a server, that's typically a GET request. POST and PUT are used to change or add data and DELETE deletes a specific resource.

This article only looks at public APIs, which usually only allow GET requests. So while we won't be using the other verbs, it's important you know they exist. It's a must-have for many web apps.

When Building an App

In your time as a developer, you might work for a company creating an application. If you're working as a frontend developer, you'll be provided API endpoints by your backend developers, along with directions for how to make requests and what to expect in return.

If you're working as a backend developer, it's your job to design and implement the APIs that run functions and query the database. You'll want to provide your frontend developers with clear documentation on how the API works.

If you're full-stack or building your own app, you might need to handle both parts. Luckily if you're using services like Auth0 for identity management, the creation of the API is handled for you.

Working with JSON

Most HTTP APIs you use will take and receive data in the JSON (JavaScript Object Notation) format. It makes learning how to read and write this format a pretty essential skill. JSON keeps its data in key-value pairs. Let's look at the JSON we get back when we request data from the Star Wars API. If we request this URL:

<https://swapi.dev/api/people/5/>

We will receive this JSON response:

{
    "name": "Leia Organa",
    "height": "150",
    "mass": "49",
    "hair_color": "brown",
    "skin_color": "light",
    "eye_color": "brown",
    "birth_year": "19BBY",
    "gender": "female",
    "homeworld": "<http://swapi.dev/api/planets/2/>",
    "films": [
        "<http://swapi.dev/api/films/1/>",
        "<http://swapi.dev/api/films/2/>",
        "<http://swapi.dev/api/films/3/>",
        "<http://swapi.dev/api/films/6/>"
    ],
    "species": [],
    "vehicles": [
        "<http://swapi.dev/api/vehicles/30/>"
    ],
    "starships": [],
    "created": "2014-12-10T15:20:09.791000Z",
    "edited": "2014-12-20T21:17:50.315000Z",
    "url": "<http://swapi.dev/api/people/5/>"
}

You can see the key/value relationship here. The key "name" has a value of "Leia Organa". We can use this object in our JavaScript code to display the information we choose or even make follow-up API requests.

If we were to query for https://swapi.dev/api/people/6/, the keys (name, height, mass) would remain the same, but the values (Leia Organa, 150, 49) would change.

JSON is a lightweight format that can be used across JavaScript, Python, PHP, and any other language you might be using on the web.

How to make an API integration?

Now that we have a better understanding of what APIs are, let's look at the integration process of an actual API and make our first requests. We're going to start simple with a joke API.

First, head to this URL.

The entire documentation takes place in this README.md file.

Looking at the documentation, I can see that we're given three endpoints.

If we want to "grab a random joke," we are given two possible syntaxes for this. There's nothing inherently different about those two links; the API author gives you two ways to approach using the API.

With this API, you can visit the URL in your browser, and you'll see the response.

Dev tip: Firefox is great at formatting the data in an easy-to-read way.

In return for our request, we receive a JSON payload with four properties: the id of this random joke, its type, the setup, and the punchline for the joke.

Note that more complicated APIs will describe exactly what you'll receive in return. If you want to see a more complex response, take a look at this Yelp API endpoint for a business.

Looking Under the Hood

One thing I like about this jokes API is that it's relatively simple and open source. It allows us to look at the code that's returning our jokes.

All of the jokes are stored in a JSON file here. When we make our GET request, index.js is what handles our request by calling the appropriate function. The functions are stored here in handler.js, and there's only a handful of functions.

I recommend taking a look through those three files, even if you don't fully understand what they're doing. You'll see that APIs don't need to be complicated. Here the 'database' is a single JSON file.

Using an API Tool - Postman

When we make API requests, it's not usually by typing them into a browser but through code. It can be time-consuming to code out API requests when you're just trying to test if an API works. Luckily there's a free program called Postman that you can download here.

Postman is a robust program that I won't get too deep into, but I want you to be comfortable with creating a GET request with it.

Download, install, and open Postman. The HTTP action verb defaults to GET, so you can leave that and paste https://official-joke-api.appspot.com/random_joke as the request URL.

Click Send to send your request, and you'll see your response in the bottom panel.

That's it! You get a whole lot of information easily accessible with Postman. You can see the status, 200 OK, the time the request took to finish, and a lot more if you navigate the different tabs.

Now hit this endpoint in Postman: https://official-joke-api.appspot.com/random_ten

We're now requesting an array of ten joke objects, so the response's shape has changed.

Notice that the response body now begins with square brackets, [ ] instead of curly brackets, { }.

Some APIs like the Unsplash API return an actual image for the response payload. Try this endpoint and see what you get: https://source.unsplash.com/random

Getting familiar with Postman will help as you continue to use APIs and someday create your own.

How to use API to make a Joke Web App

Now that we've made this request a couple of ways and see what it returns, let's use the jokes API to create a little app.

We want our app to have a "Get Joke" button that triggers an API request. When the response returns from the API, we can display the setup and punchline to the user. When the button is clicked again, it makes a new request and displays the new joke.

We don't need any libraries or plugins to do this. We'll be using regular JavaScript to make the request.

I've built a CodePen starter that has some CSS already set up. Click here to open the starter pen and click "Fork" at the bottom right to create a copy of it.

Here's the final version if you want to check out what we're making.

💡 Having a bit of experience with HTML and JavaScript will be helpful here, but I hope you can still follow along if you're just beginning.

Adding HTML

We'll start by creating our HTML. We don't need much for this demo: just a button and two paragraph elements.

<button id="button" type='button'>Get Joke</button>
<p id="setup"></p>
<p id="punchline"></p>

Make sure you include the ids and type="button" as shown. The ids have some styling tied to them, and we're going to reference them later in our JavaScript. The type="button" tells the browser that this isn't a typical form submission button.

Your CodePen window should look something like this:

Adding JavaScript

Now we'll move into the JavaScript window and make that button operational. First, we're going to add a click listener to the document.

document.addEventListener("click", function (event) {
  // Checking if the button was clicked
  if (!event.target.matches("#button")) return;

  console.log("Button was clicked!");
});

Here we're listening for all clicks. If anything that isn't the button gets clicked, we'll return, and the console.log() won't run. But if the button is the target, then we'll see our message in the console. Click the "Console" button at the bottom left of the CodePen UI to see that output.

At this time, we know our button works. Let's make it request our joke. We'll delete the line with the console.log() and replace it with a fetch() command.

Fetch is a web API! It provides us an interface to make requests and fetch resources. It's built into modern browsers and makes requesting data much easier. Read more here.

document.addEventListener("click", function (event) {
  // Checking if the button was clicked
  if (!event.target.matches("#button")) return;

  fetch("<https://official-joke-api.appspot.com/random_joke>")
    .then((response) => response.json())
    .then((data) => console.log(data));
});

We've added three lines here, the fetch() and two instances of .then(). Let's look at each line one by one.

  fetch("<https://official-joke-api.appspot.com/random_joke>")

Here we're using the Fetch API to request our joke endpoint. Like with Postman, the GET verb is the default, so we don't need to specify that. fetch() will send this request, and when it resolves or completes, it will pass the response data to our first .then().

.then((response) => response.json())

The period in front of the then() function means we are chaining our fetch request. This line of code will only run after the fetch has been resolved. fetch() returns a Response object, but we just want a JavaScript object, so we run the response.json() command. The result of that gets passed to our next line of code.

.then((data) => console.log(data));

We're chaining again and logging out the JSON that resolves from above. Click the button and check your console. It should look something like this.

This is great; we're successfully fetching data from the API with JavaScript! Now we'll display the joke in our HTML elements.

We'll add a function to the bottom of our JavaScript called renderJoke. It'll take the object we get back from the endpoint and add each element's innerHTML.

function renderJoke(data) {
  const setup = document.getElementById("setup");
  const punchline = document.getElementById("punchline");
  setup.innerHTML = data.setup;
  punchline.innerHTML = data.punchline;
}

Now change the last line of our fetch() chain from this:

.then((data) => console.log(data));

To this:

.then((data) => renderJoke(data));

Instead of logging out the data, we're now passing it to our new function. Your JavaScript should look like this:

document.addEventListener("click", function (event) {
  // Checking if the button was clicked
  if (!event.target.matches("#button")) return;

  fetch("<https://official-joke-api.appspot.com/random_joke>")
    .then((response) => response.json())
    .then((data) => renderJoke(data));
});

function renderJoke(data) {
  const setup = document.getElementById("setup");
  const punchline = document.getElementById("punchline");
  setup.innerHTML = data.setup;
  punchline.innerHTML = data.punchline;
}

When you click the button, it should return a joke like this:

If you've got this working, congratulations! You're now making an API request with JavaScript, handling the response, and displaying the results in HTML! That's a huge accomplishment. 👏

Handling Errors

Sometimes API requests don't succeed, and we need our websites or apps to let the user know something didn't go as planned. It's a pretty bad user experience to click a button, and nothing happens. Let's simulate that by adding a typo to the API endpoint. I've changed my string to "<https://official-joke-api.appspot.com/random_jo>" to force an error.

Now click the joke button. It seems like nothing happens, but if you open your developer tools and check the console, you'll see that the API responded to our request with a 404. It is the API saying it couldn't find what you're requesting.

Let's add some code to let the user know when our API returns an error.

First let's add a new paragraph element to our HTML with id="error".

<button id="button" type='button'>Get Joke</button>
<p id="setup"></p>
<p id="punchline"></p>
<p id="error"></p>

We'll then create a renderError() function to add a message to that HTML element when we get an error.

function renderError() {
  const error = document.getElementById("error");
  error.innerHTML = "Whoops, something went wrong. Please try again later!";
}

Now we're going to add a special function to our fetch() chain that catches any errors.

fetch("<https://official-joke-api.appspot.com/random_jo>")
    .then((response) => response.json())
    .then((data) => renderJoke(data))
    .catch(() => renderError());

If the fetch request succeeds the .then() functions will be called in order and the .catch() function won't be called. But if the request fails, it'll skip the .then() functions and call the .catch() only.

Click the button; now the user is notified that the request failed.

Last, we need to clear out the error message if the user tries again and the request succeeds. Add this code to our renderJoke() function.

const error = document.getElementById("error");
  error.innerHTML = "";

Fix the API endpoint so that it's" <https://official-joke-api.appspot.com/random_joke>" once more.

We're all set! Here's the final app if you'd like to check it against your code.

Extra Credit

You could continue to build on this app and add some more features.

Like letting users select a category and then change that part of the API request. You could also have some way of hiding the punchline until the user has clicked another button or a couple of seconds have passed. You could even use the endpoint for ten jokes and give the user a handful of laughs without making additional requests.

I'd love to see what you come up with!

Troubleshooting APIs

Eventually, you'll run into some trouble with APIs, and you'll need to debug a problem in your code. Here are some tips on how to troubleshoot when the API isn't doing what you expect.

Check the Documentation

If you're using a publicly available API, there should be documentation to tell you how to structure your request. Make sure you're following the syntax described there. Compare their examples to what you have in your request to see what's different.

Check the Network Tab

If you're making your API requests in the browser, one of the best API troubleshooting tools is the Network tab. In Chrome, you can press Control + Shift + J in Windows or Command + Option + J on a Mac to open DevTools. Click the Network tab at the top. Now the Network tab will listen to every single request that the website makes.

Here's a request from the joke app we made earlier.

This shows us the URL we made our request to, our Method (or verb), and the status code we received in return. You can see what the API returned in the Preview and Response tabs.

If your status code isn't 200, read on.

Check the Status Code

You've seen "404 File Not Found" on a website when you clicked a dead link or typed something wrong. That 404 is a specific code that the server gives to your browser as feedback on its request.

Either in the network tab or Postman, you will always receive a status code from the API.

It's one of many HTTP status codes that help us understand how our requests are being received. The responses are grouped into hundreds:

  • 1xx informational response – the request was received, continuing process

  • 2xx successful – the request was successfully received, understood, and accepted

  • 3xx redirection – further action needs to be taken in order to complete the request

  • 4xx client error – the request contains bad syntax or cannot be fulfilled

Generally speaking, a response of 200 or anything in the 200's is a success.

Anything in the 400 's means the request failed, and the cause is probably our error. Check the list of HTTP status codes for the specific code you received. If it's a 400 you should check that your request is formatted correctly.

Anything in the 500 's means something went wrong on the server that handled your API request. The server might be down, or there might be a bug in the code. Try your request again after a little while.

CORS

When working with APIs, you're likely to someday run into what's known as a CORS (Cross-Origin Resource Sharing) error. You've got a CORS error if you check your console and see a message about "No 'Access-Control-Allow-Origin' header is present on the requested resource'.

Here's a good resource for learning about and fixing this error when you encounter it.

Issues with Promises

One thing we didn't get into in this article was the concept of Promises. When working with APIs, you begin to work with the concept of asynchronous programming. It's outside the scope of this article, but if you're having trouble working with the data that gets returned from your API requests, you might be running into an issue with Promises. Here's a great article to get you caught up.

Best API integrations to get started with

There are a ton of free APIs for you to use for whatever kind of project you'd like to make. Here's a full list of hundreds of APIs, but I'll outline a couple below with ideas on how you might get started.

Unsplash

Unsplash is a great resource for downloading completely free stock photographs, but did you know they have a public API too?

Check out Unsplash Source and think about how you can use this API to add beautiful images to your next project.

Pokemon API

The PokeAPI is a free API that doesn't require authentication to access. There are a few different endpoints available to you, which means you can ask for different kinds of data. You can query for specific Pokemon, moves, games, locations, and a lot more.

Here's a Catch Pokemon app example based on our Joke app from earlier to help you get started.

The Dog API

The Dog API returns random pictures of dogs! The best bit is you can ask for dogs in specific breeds, which gives you the chance to make a more complex web app.

If you'd like a basic concept, you could make something similar to the Pokemon app, but with another level of complexity. Take a look at some wireframes for this app idea.

This app shows a random picture of a dog but has a dropdown that lists all the breeds so the user can narrow the pool of images they receive.

First, your app could use this endpoint to receive all the breeds the API has: https://dog.ceo/api/breeds/list/all

Then you can include their selection in a request to this endpoint: https://dog.ceo/api/breed/hound/images, replacing hound with their choice.

Read the docs here to see what that will return. That should get you started!

No-Code API integration platforms

We aren't going to dig into these connector applications options much, but I want you to know these are available in case these best fit your needs.

Some services like Zapier or IFTTT provide an easy interface for people to connect different APIs to their ecosystem. They also reduce the need for API management.

This example from the Zapier homepage connects the Gmail, Dropbox, and Slack APIs. This would take a bit of time for you to code yourself, but Zapier creates an interface on top of these APIs, further abstracting the complexity!

You might be able to use "no-code" solutions like Zapier to wire up a few actions, but you're limited in what you can do. You sacrifice ease of use for flexibility. For this reason, it's good to know these tools exist and understand how to use web APIs yourself. Then you can choose the best solution for your digital transformation tasks.

Wrap Up

We touched on a lot in this article, so congrats for making it to the end.

We looked at the concepts of interfaces and how an API abstracts away complexity. We touched on web APIs and then dug deep into HTTP APIs. We used Postman to make requests and even created our Joke app! We explored a few more APIs you could play with and saw that sometimes no-code solutions could be the way to go.

I hope you learned a lot and feel more confident working with APIs in the future. While some APIs can be incredibly complex, the underlying concepts remain the same.

About the author

Alex Trost
Developer

Demystifying frontend techniques on FrontendHorse and developer experience at Prismicio

Follow him on Twitter!

Recent articles in Web Development

36 000+ geeks are getting our monthly newsletter: join them!