The Fetch API is the standard way to make HTTP requests from JavaScript in the browser. It replaces the older XMLHttpRequest with a cleaner, promise-based interface, and it handles the jobs modern front-end code needs most: loading JSON data, submitting forms, uploading information to an API, and refreshing part of a page without a full reload. If you understand a handful of fetch api javascript examples covering GET, POST, headers, and error handling, you can talk to almost any REST API you will meet in everyday work.
Fetch is built into all modern browsers and also available in Node.js 18 and later, so the same basic patterns work on both sides. Two facts explain most beginner confusion. First, fetch() returns a promise that resolves to a Response object, not directly to your data, so you need a second step to read the body as JSON or text. Second, fetch only rejects its promise on network failures. An HTTP 404 or 500 response still resolves successfully, which means you must check the response status yourself. Keep those two ideas in mind and the examples below will make complete sense. For controlling how often requests fire from typing or scrolling, pair fetch with the utilities in our debounce and throttle guide.
A Basic GET Request With async and await
The most common request is a GET that loads JSON. The modern style wraps fetch in an async function and uses await, which reads almost like synchronous code while still being non-blocking. The example below loads a single post from a public test API and logs its title.
async function getPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data.title);
console.log(data.body);
}
getPost();
Step by step, fetch is called with just a URL, which defaults to a GET request. The await pauses inside this async function until the response headers arrive, without freezing the rest of the page. The returned Response object holds metadata like status and headers plus methods to read the body. Calling response.json() reads the body stream and parses it as JSON, returning another promise, so we await that too. Only after both awaits do we have a normal JavaScript object we can use. If the API returned plain text instead, you would use response.text(), and for files you would use response.blob(). Each body method can only be used once per response, so choose the right one first time.
Checking the Response Status Properly
Because fetch does not throw on HTTP errors, checking response.ok is not optional. The ok property is true for status codes from 200 to 299 and false otherwise. Good fetch code checks it before trying to use the data, and throws a descriptive error when the check fails so a surrounding catch block can handle all failures in one place.
async function getUser(userId) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const user = await response.json();
return user;
}
try {
const user = await getUser(1);
console.log(user.name, user.email);
} catch (error) {
console.error("Could not load user:", error.message);
}
The function builds its URL with a template literal so the user ID is inserted neatly. After the fetch, it tests if (!response.ok) and throws an Error that includes the numeric status, such as 404 for a missing user. The caller wraps the call in try...catch, so both network failures and the thrown HTTP error land in the same catch block, where we log a friendly message. Returning the parsed user from the function, rather than logging inside it, keeps the fetching code reusable in different pages. Once you have the user object, transforming a list of such objects for display is easy with the techniques in our JavaScript array methods cheat sheet.
Sending a POST Request With JSON
To create or submit data, use a POST request with a second argument to fetch: an options object describing the method, headers, and body. APIs that accept JSON expect the Content-Type header to be set to application/json and the body to be a JSON string, which you produce with JSON.stringify. Forgetting either step is the most common cause of a server rejecting an otherwise correct-looking request.
async function createPost(title, body) {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: title,
body: body,
userId: 1
})
});
if (!response.ok) {
throw new Error(`Create failed with status ${response.status}`);
}
const created = await response.json();
console.log("New post ID:", created.id);
return created;
}
createPost("Hello Fetch", "This post was sent with fetch.");
The options object is where fetch gets its power. The method property switches the request from GET to POST. The headers object tells the server how to interpret the body. The body property carries the actual payload, and it must be a string for JSON APIs, which is why we stringify a normal object first. A successful create usually returns status 201 and the saved record, often including a new ID generated by the server. The same options pattern covers PUT and PATCH for updates and DELETE for removals; only the method name and URL change. Submitting a traditional HTML form follows similar thinking, and the server side of that exchange is covered in our PHP form handling basics.
Sending Form Data Without JSON
Not every endpoint wants JSON. File uploads and classic form endpoints expect multipart form data. Fetch makes this easy with the FormData object: you append fields to it and pass it as the body, and the browser sets the correct Content-Type header automatically, including the boundary marker the format requires. Do not set that header yourself in this case, or uploads will break.
async function uploadAvatar(fileInput) {
const formData = new FormData();
formData.append("avatar", fileInput.files[0]);
formData.append("username", "haseeb");
const response = await fetch("https://example.com/upload", {
method: "POST",
body: formData
});
if (!response.ok) {
throw new Error(`Upload failed with status ${response.status}`);
}
const result = await response.json();
console.log("Uploaded:", result);
}
Here we create an empty FormData instance and append two fields: the file taken from a file input element, and a plain text username. Because the body is a FormData object rather than a string, fetch handles encoding for us. This example uses a placeholder domain because upload endpoints are specific to your own server; replace the URL with your real endpoint when adapting it. The key takeaway is the contrast with the JSON example: same fetch call, different body type, and the header handling changes accordingly.
Adding Headers and Authentication Tokens
Many APIs require an authorization header with a token, or a custom header for versioning. Headers are just key-value pairs in the options object, alongside Content-Type. Keep tokens out of your source files in real projects; read them from a configuration value or from storage set at login, and never commit real credentials to a public repository.
async function getMyOrders(token) {
const response = await fetch("https://api.example.com/orders", {
method: "GET",
headers: {
"Authorization": `Bearer ${token}`,
"Accept": "application/json"
}
});
if (!response.ok) {
throw new Error(`Orders failed with status ${response.status}`);
}
return response.json();
}
The Authorization header here uses the Bearer scheme, which is the most common token format for REST APIs: the word Bearer, a space, then the token itself, built with a template literal. The Accept header tells the server we want JSON back. Returning response.json() directly is a compact shortcut; the caller still needs to await it, because json() returns a promise and an async function automatically passes that promise through. If you store a token between page loads, the storage patterns in our localStorage guide show how to save and read it, along with the security warning that tokens in localStorage must never hold highly sensitive credentials for high-risk apps.
Handling Errors Completely: Network, HTTP, and Parsing
Robust fetch code separates three failure kinds. Network errors, such as no connection or a DNS failure, reject the fetch promise and land in catch. HTTP errors resolve the promise but set ok to false, which is why the explicit check matters. Parsing errors happen when the body is not valid JSON and response.json() throws. A single try and catch around the whole operation handles all three if you check ok inside the try block.
async function loadProducts() {
try {
const response = await fetch("https://dummyjson.com/products?limit=5");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
data.products.forEach((product) => {
console.log(product.title, product.price);
});
} catch (error) {
console.error("Loading products failed:", error.message);
}
}
loadProducts();
This function is a tidy template for read-only loading. Everything risky sits inside the try block: the fetch itself, the status check, and the JSON parsing. Any failure at any step jumps straight to the catch block, which logs one consistent message. In a real interface you would also update the page in the catch block, for example showing a “could not load products, please retry” notice and a retry button that calls the function again. Showing an error state instead of leaving a blank area or an endless spinner is a small detail that users notice and appreciate. Also consider showing a loading indicator before the fetch and hiding it in a finally block so it disappears on both success and failure.
Cancelling a Request With AbortController and Timeouts
Sometimes a request needs to be cancelled: the user navigates away, types a new search term, or the request simply takes too long. Fetch supports cancellation through AbortController. You create a controller, pass its signal in the options, and call abort() when you want to stop. The fetch promise then rejects with an abort error you can recognise and ignore. The same mechanism gives you a simple timeout pattern.
async function fetchWithTimeout(url, timeoutMs) {
const controller = new AbortController();
const timerId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, { signal: controller.signal });
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return await response.json();
} finally {
clearTimeout(timerId);
}
}
// Example: give the request 5 seconds
fetchWithTimeout("https://dummyjson.com/products/1", 5000)
.then((product) => console.log(product.title))
.catch((error) => console.error("Failed:", error.name, error.message));
The controller is created first, and a timer is set to abort it after the given number of milliseconds. The signal is passed to fetch, linking the two. If the response arrives in time, the finally block clears the timer so it cannot fire pointlessly later. If the timer fires first, fetch rejects with an error whose name is AbortError, which the catch block can check to distinguish a timeout from other failures. This pattern is especially valuable for search-as-you-type features, where aborting the stale request prevents an older, slower response from overwriting newer results on the page.
Using the Promise Style Without async and await
Before async and await became common, fetch code was written with .then() chains, and you will still meet this style in older codebases and quick scripts. Both styles use the same underlying promises, so choose whichever your project already uses and stay consistent.
fetch("https://jsonplaceholder.typicode.com/posts/2")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((post) => {
console.log(post.title);
})
.catch((error) => {
console.error("Request failed:", error.message);
});
The first then receives the Response, checks the status, and returns the promise from response.json(). Returning that promise is essential, because the second then waits for it and receives the parsed object. Throwing inside a then rejects the chain, so the single catch at the end handles HTTP errors, network errors, and parsing errors together, just like try and catch in the async style. The logic is identical; only the syntax differs.
Conclusion
Fetch becomes straightforward once you follow a consistent recipe: call fetch with a URL and options, check response.ok, read the body with json() or text(), and handle errors in one place. Use GET for reading, POST with a JSON string body and the correct header for creating, FormData for uploads, and AbortController when you need cancellation or timeouts. Copy the templates from this note, swap in your own endpoints, and always test the failure paths as well as the success path, because well-handled errors are what separate a fragile demo from reliable code.




4 thoughts on “Fetch API Examples: GET, POST and Error Handling in JavaScript”