Now you know how to use the fetch()
function to fetch the content at a URL, including JSON content. An example might look like this:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
This code calls the fetch()
function to fetch the JSON content at this URL:
https://happycoding.io/tutorials/javascript/example-ajax-files/random-welcomes.json
It then processes the response to convert the JSON into an array. Finally, it gets a random object from the array and uses that to show a message in the page.
This approach of using JavaScript to fetch and add content to a webpage is generally called AJAX. But the fetch()
function also unlocks another cool ability: using APIs!
API stands for Application Programming Interface, and broadly speaking, an API is a way for one program to talk to another. There are many different APIs, but in the world of web development, you’ll most often be using an HTTP-based API, which is sometimes called a RESTful API.
All of that sounds confusing at first, but here’s an example:
https://xkcd.vercel.app/?comic=722
“But wait, that’s just a URL. I thought we were learning about APIs?”
That’s pretty much what a web API is! Or rather, an API is a set of endpoints (URLs) that you can use to interact with some underlying data.
Try visiting that URL, and you should see some JSON content like this:
{
"month": "4",
"num": 722,
"link": "",
"year": "2010",
"news": "",
"safe_title": "Computer Problems",
"transcript": "[[A man and a woman are looking at his computer, on the desk.]]\nMan: You know this metal rectangle full of little lights?\nWoman: Yeah.\n\nMan: I spend most of my life pressing buttons to make the pattern of lights change however i want.\nWoman: Sounds good.\n\nMan: But today, the pattern of lights is ALL WRONG!\nWoman: Oh god! Try pressing more buttons!\nMan: IT'S NOT HELPING!\n\n",
"alt": "This is how I explain computer problems to my cat. My cat usually seems happier than me.",
"img": "https://imgs.xkcd.com/comics/computer_problems.png",
"title": "Computer Problems",
"day": "2"
}
This is a JSON object that contains fields that correspond to this XKCD comic: https://xkcd.com/722/
“Why would I want to look at the JSON instead of the comic?”
The JSON is not meant for a human to look at, it’s designed for code to read!
For example, you could fetch the JSON to create your own webpage based on the data:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
This code defines a fetchXkcd()
function which is called on page load. The function then fetches the above URL, converts it into a JSON object, and uses its fields to add content to the page.
That’s the power of web APIs: you can write code and build websites based on other people’s data!
Remember, an endpoint is really a URL. You can build URLs out of string values in JavaScript, which means you can do things like base them off user input.
Here’s another example:
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
This page contains an input and a button, and calls the fetchXkcd()
function when the user clicks. The function gets the ID from the input and builds a URL out of it:
let id = document.getElementById('comic-id').value;
let url = 'https://xkcd.now.sh/?comic=' + id;
let response = await fetch(url);
let json = await response.json();
There’s nothing too special about this URL. It’s a string in JavaScript, but it’s still a URL that you can navigate to in your browser. Try entering a number above and then clicking the button, and then navigating to the corresponding URL in your browser to see the underlying JSON.
Challenge: Modify the above code to show a random XKCD comic if the number input is blank!
I’m using an API built around the XKCD comic because it’s relatively small and fun to play with, but there are many APIs out there.
Try searching for something you’re interested in, followed by JavaScript API
or web API
. For example, I searched for books JavaScript API
and found the Open Library API.
That page contains the documentation for the API, which contains a list of URLs that give different kinds of data. Similar to learning how to use a JavaScript library, reading through the documentation is the first step to learning how to use an API!
For example, the documentation for the Open Library Search endpoints lists ways to search for authors and books.
Here’s an example endpoint:
https://openlibrary.org/search.json?q=Daniel+Shiffman
If you navigate to the above endpoint URL, you might be overwhelmed at first. That’s a lot of JSON!
Remember that JSON is not really meant to be read by a human; it’s meant for code. But you can click through the response to better understand it. Most browsers automatically format it, or you can use a JSON formatter to prettify it.
Either way, try clicking around in the JSON to understand its contents.
You can also read through the API documentation to get a better sense of what to expect from a response.
The APIs and endpoints we’ve seen so far are all public and open, meaning you can access them via URLs without providing any information about who you are.
However, many APIs require an API key, which is usually a random sequence of letters and numbers that’s unique to you or your project. You can pass this key into the endpoint, and the API will know where the request came from.
For example, NASA offers a ton of APIs that require an API key: https://api.nasa.gov/#browseAPI
Try navigating to this endpoint URL:
https://api.nasa.gov/planetary/apod
You’ll get an error that says you need an API key. You can pass one in as a query parameter:
https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY
This URL uses a special DEMO_KEY
value that NASA’s API supports for trying out endpoints, but it only works for the first few tries. To unblock it, you need an API key that’s unique to you.
Obtaining an API key usually means signing up for an account, but with NASA’s API it means submitting a form with your email: https://api.nasa.gov:443
When you fill out the form, you’ll receive an email with your own API key that you can use in your code.
I’m using NASA’s API as an example, but many APIs require keys. The process for obtaining a key might be a little different depending on the API, but in general you’ll likely sign up for an account and then follow a process to get a key. See the documentation for your API for more info.
API keys are one of the most common forms of authentication used by web APIs, but there are many others.
These are often related to billing- every API I listed above has been free, but many APIs charge money to use them! Complex authentication can also be related to taking action in a user’s account, like adding a song to a user’s Spotify playlist.
For now, I’m going to consider complex authentication out of scope for this tutorial. If you’re new to APIs, start with an open API, or an API that gives you an API key!
Warning: If an API asks for billing information, or talks about a secret key or other private credentials, be careful so you don’t accidentally get a bill or leak your credentials to hackers!
Again, the APIs and endpoints we’ve seen so far are all public and open, meaning you can access them from your browser. But some APIs are meant to be accessed from a server, rather than a browser.
If you try to access an endpoint and you get a CORS error, chances are the endpoint is not meant to be accessed from JavaScript in a browser.
I’m also going to consider CORS errors out of scope for this tutorial. If you’re new to APIs, start with an API that can be access from JavaScript in a browser!
Most APIs limit how many times you can call them in a given time- usually per minute, hour, or day. This is to prevent people from accidentally or intentionally overloading the service.
For example, the NASA API limits you to 1,000 requests per hour. That might sound like a lot, but it quickly adds up as you’re coding and refreshing the page a lot.
With rate limits in mind, be careful with repeated code like for loops. This code would eat through those 1,000 requests immediately:
for (let i = 0; i < 100000; i++){
fetch('https://api.nasa.gov/planetary/apod?api_key=YOUR_API_KEY');
}
(Don’t actually run this code!)
If you go over your rate limit, it usually means you need to wait for your limit to be reset- generally within an hour, or sometimes a day. This can be annoying, so try not to hit your limit!
Another thing to keep in mind is that as you share your project and more people start using it, your API usage will increase. For small projects, that’s not usually a concern, but think about what would happen if your site went viral and you suddenly had a million people clicking around.
Many API services offer paid tiers with higher rate limits, but for now, free APIs should get you pretty far.
You can find APIs related to pretty much any topic, and I recommend searching for them. But here are a few I’ve found that seem fun, with an example endpoint for each. Try clicking each and seeing what kind of data you get back:
https://openlibrary.org/search.json?q=Daniel+Shiffman
https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2024-03-19
https://restcountries.com/v3.1/alpha/ca
http://numbersapi.com/37/trivia?json
https://api.chucknorris.io/jokes/random?category=animal
https://pokeapi.co/api/v2/pokemon/snorlax
https://www.thecocktaildb.com/api/json/v1/1/search.php?s=gin+and+tonic
https://www.amiiboapi.com/api/amiibo/?character=sonic
https://www.themealdb.com/api/json/v1/1/search.php?s=chocolate
https://anapioficeandfire.com/api/characters/583
https://v2.jokeapi.dev/joke/Spooky
https://en.wikipedia.org/w/api.php?action=parse&page=Cat&format=json&origin=*
https://mamot.fr/@pluralistic.json
https://gateway.marvel.com:443/v1/public/characters?name=Squirrel%20Girl&apikey=YOUR_API_KEY
This is a list of random APIs that I found poking around for a few minutes. I strongly encourage you to look for APIs related to something you’re interested in!
What are you waiting for? Go find an API and make something cool!
I posted a new article about fetching data from APIs. This lets you work with data from other sources!
Check it out here:
Interact with data from API endpoints.
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!
Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!