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+Shiffmanhttps://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2024-03-19https://restcountries.com/v3.1/alpha/cahttp://numbersapi.com/37/trivia?jsonhttps://api.chucknorris.io/jokes/random?category=animalhttps://pokeapi.co/api/v2/pokemon/snorlaxhttps://www.thecocktaildb.com/api/json/v1/1/search.php?s=gin+and+tonichttps://www.amiiboapi.com/api/amiibo/?character=sonichttps://www.themealdb.com/api/json/v1/1/search.php?s=chocolatehttps://anapioficeandfire.com/api/characters/583https://v2.jokeapi.dev/joke/Spookyhttps://en.wikipedia.org/w/api.php?action=parse&page=Cat&format=json&origin=*https://mamot.fr/@pluralistic.jsonhttps://gateway.marvel.com:443/v1/public/characters?name=Squirrel%20Girl&apikey=YOUR_API_KEYThis 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!