JavaScript Fetch API
Connect your website to real information! Learn how JavaScript requests data from an API, waits for a response, converts JSON, and updates a webpage dynamically.
async function loadData() {
const response =
await fetch("/api/data");
const data =
await response.json();
console.log(data);
}
What Is an API?
Imagine building a website that displays the latest weather, a list of books, or information about users. You could type all that information into your HTML manually, but what happens when the information changes?
An API (Application Programming Interface) provides a defined way for software systems to communicate. Many web APIs allow JavaScript to request information over HTTP.
The Fetch API gives JavaScript a built-in way to make those requests.
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data.name);
});This example requests a user record from JSONPlaceholder, a public service designed for practicing API requests.
How Does fetch() Work?
When JavaScript calls fetch(), the browser starts an HTTP request and returns a Promise. A Promise represents an operation whose result may become available later.
const request = fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
console.log(request); // A PromiseThe browser doesn’t need to freeze while waiting for the server. Other page interactions can continue.
Once the response arrives, you can inspect its HTTP status and read the response body.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(function(response) {
console.log(response.status);
console.log(response.ok);
});response.status is the HTTP status code. response.ok is true for successful HTTP statuses in the 200–299 range.
response.ok yourself.Write Asynchronous Code More Clearly
Promises can be handled with .then(), but JavaScript also provides async and await for writing asynchronous code in a readable style.
async function loadUser() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
if (!response.ok) {
throw new Error("Request failed");
}
const user = await response.json();
console.log(user.name);
}
loadUser();async marks a function as asynchronous. await pauses that function until the awaited Promise settles, without blocking the entire webpage.
Notice the two await expressions: one waits for the response, and the second waits for the response body to be read and parsed as JSON.
Turn Responses Into Webpage Content
After retrieving data, you can use DOM methods to show it on the page.
async function showUser() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
if (!response.ok) {
throw new Error("Unable to load user");
}
const user = await response.json();
document.getElementById("username").textContent =
user.name;
}For multiple records, use forEach() to create a card for each item.
const container = document.getElementById("results");
users.forEach(function(user) {
const card = document.createElement("div");
card.textContent = user.name;
container.appendChild(card);
});textContent when displaying text received from an API. Avoid placing untrusted data directly into innerHTML.Help Visitors Understand What’s Happening
Network requests can take time or fail. A good website tells visitors when information is loading, when it succeeds, and when something goes wrong.
async function loadData() {
const status = document.getElementById("status");
status.textContent = "Loading...";
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
const users = await response.json();
status.textContent = users.length + " users loaded.";
} catch (error) {
status.textContent = "Unable to load data.";
} finally {
console.log("Request finished.");
}
}try contains the request, catch handles failures, and finally runs when the operation finishes—even if an error occurred.
Some requests fail because of connectivity, server problems, browser restrictions, or cross-origin access rules (CORS).
Filter, Search, and Refresh Information
Once API data is loaded into an array, you can use the same JavaScript techniques you’ve already learned.
const filtered = users.filter(function(user) {
return user.name.toLowerCase().includes("a");
});
filtered.forEach(function(user) {
console.log(user.name);
});You can also add a Refresh button that calls your loading function again.
const refreshButton =
document.getElementById("refresh");
refreshButton.addEventListener("click", loadData);These small additions make a static webpage feel like an application.
Try the Live API Explorer
Let’s retrieve public user records from JSONPlaceholder. You can load live records or use built-in sample data if the request is unavailable.
Request a list of users and see how JavaScript turns JSON into readable content.
Try the live request first. Then compare it with the sample-data option. Both produce the same kind of JavaScript array, even though the data comes from different sources.
Build an API Data Dashboard
Create a dashboard that retrieves user information from an API and displays it as attractive cards.
Your Mission
- Create a button labeled Fetch Users.
- Use
fetch()to request user records from JSONPlaceholder. - Use
asyncandawaitto handle the request. - Check
response.okbefore reading the JSON. - Display each user’s name, email address, and company.
- Show loading, success, and error messages.
- Add Refresh and Sample Data buttons.
Build Your API Data Dashboard!
The starter project includes a working API request, error handling, user cards, and sample data. Load Solution adds search, result counts, and a polished dashboard layout.
Live requests require internet access and permission from the API’s cross-origin policy. The sandbox uses an isolated iframe; its sample data works without external requests.
What You’ve Learned
You’re Connecting JavaScript to Real Data!
You’ve learned how webpages communicate with APIs and how to turn responses into useful interfaces.
- Understand what APIs do and how HTTP requests work.
- Use
fetch()to request information. - Write asynchronous code with
asyncandawait. - Read JSON responses using
response.json(). - Display API results using DOM methods.
- Handle loading, success, and error states.
- Build an interactive API Data Dashboard.
Next up: Local Storage — learn how to remember information even after a visitor refreshes or closes a webpage!
Your Learning Journey
0 / 17 CompletedLesson 15 of 17 — only Local Storage and the Final Project remain!
You've Mastered Fetch API Basics!
You can now request data from APIs, work with asynchronous JavaScript, handle loading and errors, and display real information on a webpage. You've built your own API Data Dashboard!


