API Beginner
API Beginner
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.
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.
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.
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 "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 .
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.
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.
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.
JSON is a lightweight format that can be used across JavaScript, Python, PHP, and any
other language you might be using on the web.
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.
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.
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.
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.
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.
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 = "";
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.
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.
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.
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.
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
Read the docs here to see what that will return. That should get you started!
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.