JavaScript Fetch API for Beginners: Get Data Step by Step
Learn how to use the JavaScript fetch API for beginners: get data from a URL, read JSON, show it on a page and handle errors, with simple copy-paste examples.
Learn how to use the JavaScript fetch API for beginners: get data from a URL, read JSON, show it on a page and handle errors, with simple copy-paste examples.
How do you use the JavaScript fetch API? Short answer: fetch() is a built-in JavaScript function that asks another computer (a server) for data over the internet. You give it a web address, wait for the answer, and then turn that answer into something your code can use, usually JSON. This guide shows you how, one small step at a time.
You do not need any special tools. If you know what a variable and a function are, you can follow along. Every new word is explained the first time it appears.
An API (Application Programming Interface) is a way for one program to talk to another. A web API is an address on the internet that sends back data when you ask for it. The fetch API is the tool built into your browser that lets JavaScript make that request.
Think of it like ordering food. You (your code) ask the waiter (fetch) for a dish. The kitchen (the server) prepares it. The waiter comes back later with your food (the data). You do not stand frozen at the counter while you wait, and that is where async code comes in.
Getting data from the internet takes time. JavaScript does not stop and wait. Instead, fetch() returns a promise. A promise is an object that means: "I do not have the answer yet, but I will give it to you later." We use the word await to pause inside a function until the promise is ready.
If async and await are new to you, read our guide first, then come back here.
New to the await keyword? Read this short guide first, then return to fetch.
JavaScript Async/Await for BeginnersWe will use a free practice API called JSONPlaceholder. It returns fake data, so you cannot break anything. Open your browser, press F12, click the Console tab and paste this code.
async function getUser() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log(user.name);
}
getUser();Line 1 creates an async function, which is a function allowed to use await. Line 2 calls fetch with a web address and waits for the response. The response is the full reply from the server. Line 3 calls response.json(), which reads the reply and turns it into a JavaScript object. It also returns a promise, so we await it too. Line 4 prints the user's name. The last line runs the function. You should see "Leanne Graham" in the console.
JSON (JavaScript Object Notation) is a text format for sharing data. It looks almost the same as a JavaScript object, which makes it easy to use. Most web APIs send data as JSON.
{
"id": 1,
"name": "Leanne Graham",
"email": "Sincere@april.biz"
}This is what the server sends. Each line is a key and a value, like "name" and "Leanne Graham". After response.json(), you read a value with a dot, for example user.email.
Many APIs return a list, which JavaScript stores as an array. The ?_limit=3 at the end of the address asks for only three items.
async function getPosts() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
const posts = await response.json();
for (const post of posts) {
console.log(post.title);
}
}
getPosts();The first two lines inside the function work just like before. This time posts is an array. The for...of loop visits each item one at a time, and console.log prints the title of each post. You will see three titles in the console.
Printing to the console is nice for practice, but real users need to see data on the page. Here is a small page that loads posts and displays them in a list.
<ul id="post-list"></ul>
<script>
async function showPosts() {
const list = document.getElementById("post-list");
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
const posts = await response.json();
for (const post of posts) {
const item = document.createElement("li");
item.textContent = post.title;
list.appendChild(item);
}
}
showPosts();
</script>The empty ul is where the list will go. Inside the script, document.getElementById finds that list. After fetching the posts, the loop creates a new li element for each one, sets its text to the post title, and adds it to the list with appendChild. Always use textContent, not innerHTML, when showing data from outside. It keeps the page safe from harmful code.
Things go wrong. The internet can drop, or the address can be wrong. Two tools help: the response.ok property and try...catch.
Here is a surprise that trips up many beginners: fetch does not fail when the server says "not found" (status 404) or "server error" (status 500). It only fails if the request cannot be made at all. So you must check response.ok yourself. It is true when the status is in the 200 range, which means success.
async function getUserSafely(id) {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/" + id);
if (!response.ok) {
throw new Error("Request failed with status " + response.status);
}
const user = await response.json();
console.log(user.name);
} catch (error) {
console.log("Something went wrong:", error.message);
}
}
getUserSafely(1);
getUserSafely(99999);Everything risky goes inside try. If response.ok is false, we throw an error on purpose, which jumps straight to catch. The catch block receives the error and prints a friendly message instead of crashing. The first call works. The second asks for a user that does not exist, so you see the error message.
By default, fetch makes a GET request, which means "give me data". To send data, for example a new post, use a POST request. You pass a second argument, an object of options.
async function createPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", body: "My first post", userId: 1 })
});
const result = await response.json();
console.log(result);
}
createPost();The method option says we are sending data. The headers option tells the server the data is JSON. The body is the data itself. JSON.stringify turns a JavaScript object into JSON text so it can travel over the internet. The practice API replies with your data plus a new id.
| Part | What it does |
|---|---|
| fetch(url) | Sends a GET request and returns a promise |
| await | Waits for a promise to finish |
| response.ok | true if the status is 200-299 |
| response.json() | Turns the reply into a JavaScript object |
| JSON.stringify() | Turns an object into JSON text to send |
| try...catch | Catches errors so your page does not break |
The fetch API is a built-in browser feature that lets JavaScript request data from a server using a web address. It returns a promise, so you usually use it with async and await. It replaced older, more complicated tools like XMLHttpRequest.
Fetch is built in, so you need to install nothing. Axios is an extra library that adds small conveniences, such as automatic error handling for bad status codes. For beginners, learning fetch first is best because it teaches how web requests really work.
Network requests take time, and JavaScript should not freeze the page while it waits. A promise lets your code keep running and gives you the result later. You use await or .then() to get that result.
No. Fetch only rejects when the request itself fails, such as when there is no internet. A 404 or 500 still counts as a reply, so check response.ok and throw your own error if it is false.
Yes. Modern versions of Node.js include fetch, and it works the same way as in the browser. You can run the examples in this guide in Node.js without installing anything.
You can now request data, read JSON, show it on a page and handle errors. A great next step is to fetch data when a button is clicked. Learn how events work, then combine them with fetch to build a simple search box or a "load more" button.
Want to connect a button click to your fetch code? Learn event listeners next.
JavaScript Event Listeners for BeginnersNeed help turning what you learn into a real website or app? Talk to the Fepiq team.
Contact FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.