Key takeaways:
- The JavaScript Fetch API is a modern way to make HTTP requests, supporting Promises and clean syntax.
- Always check response status and handle errors carefully to make your Fetch requests reliable.
- Use async/await, set proper headers, and correctly parse the response body to build reliable applications.
The JavaScript Fetch API makes it easier to work with HTTP requests in the browser. It helps you fetch data from servers, post new entries, and work with APIs in a modern, cleaner way.
We’ll walk you through using the Fetch API, with examples and explanations to help you understand how to make a Fetch request, handle responses, and manage errors.
What is the Fetch API in JavaScript?
The Fetch API is a built-in browser interface for making HTTP requests. You can use it to retrieve data and interact with APIs using JavaScript.
The old way of doing it was with XMLHttpRequest, but the Fetch API is simpler and returns Promises. It means you can write asynchronous code that’s easier to read and manage.
Most modern apps and websites use it because it supports all common HTTP methods, integrates smoothly with JSON through response.json(), and provides a cleaner, Promise-based interface for handling network requests.
Fetch API syntax and structure
Here’s the basic structure of a Fetch request:
fetch(url, options)
.then(response => {
// handle the response
})
.catch(error => {
// handle errors
});
- url is the endpoint you want to call.
- options is an object that holds things like request method, headers, and request body.
The Fetch API is Promise-based, returning a Promise that resolves with a Response object. You can then call methods like response.json() or response.text() to read the body, either with .then() or using async/await.
You can use GET, POST, PUT, DELETE, and more with method in the options.
JavaScript Fetch API GET request example
You can test both the GET and POST example in the browser DevTools Console, a local HTML/JS file with a <script> tag, or a modern development environment for Node.js
Let’s say you want to fetch data from a public API:
fetch('https://api.sampleapis.com/coffee/hot')
.then(response => response.json())
.then(data => {
console.log(data);
});
In this example, we’re using .json() to parse the response body into a usable JSON object. It helps you easily retrieve data from the server.
JavaScript Fetch API POST request example
To send data, use a POST request:
fetch('https://api.restful-api.dev/objects', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John',
email: '[email protected]'
})
});
Here’s what’s happening:
- We’re using the POST request method to send data.
- We set headers with 'Content-Type': 'application/json'.
- The body is the request payload, and we use JSON.stringify() to convert the JavaScript object into a JSON-formatted string.
It’s useful for forms, user input, and similar cases.
How to use async/await with Fetch
Using async/await makes the code cleaner and easier to follow. Here’s the same Fetch request using async/await:
async function getUsers() {
try {
const response = await fetch(''https://api.sampleapis.com/coffee/hot'');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
It’s easier to read, especially with multiple steps. Plus, error handling is simpler using try/catch.
Handling errors and response statuses
To handle HTTP errors, you’ll have to check the response status yourself:
fetch(''https://api.sampleapis.com/coffee/hot'')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Always check response.ok and response.status. It helps avoid surprises when the server responds with an error.
How to set headers in Fetch API
Headers help you tell the server what you’re sending or expecting. You can set headers like this:
fetch(''https://api.sampleapis.com/coffee/hot'', {
method: 'GET',
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
}
});
Common use cases for headers:
- Sending tokens for authentication.
- Setting the Content-Type to work with JSON.
- Custom headers for APIs or proxies.
The request headers you send should match what the API expects, otherwise you’ll get an error. Always check response headers to understand what the server responds with.
You’ll often work with headers when using proxies.Take a look at our web scraping techniques to learn scraping strategies, what proxies add to the process and why headers are important.
Best practices for using Fetch API
To have the best experience possible while working with Fetch API, make sure you follow these best practices:
- Use async/await for readable asynchronous code.
- Always check the response status and response.ok.
- Implement timeouts and retries manually (e.g., with AbortController or custom logic) if the network response takes too long.
Also, you should be aware of CORS restrictions. You can adjust your request headers when allowed, but ultimately the server must send the correct CORS headers for your request to succeed.
Common use cases of Fetch API
You’ll most often find yourself using the Fetch API when you:
- Call REST APIs to fetch data.
- Work with login systems that require tokens in headers.
- Fetch external HTML or other resources (like JSON or images as blobs) dynamically.
If you’re into web scraping, you may also use Fetch API to send requests through a proxy server (configured outside Fetch, e.g., at the browser, system, or server level) to route traffic through a different location.
Fetch API vs Axios vs XMLHttpRequest
Fetch API is native, Promise-based, and works great for most cases. But:
- Axios provides conveniences like automatic JSON parsing (when the response has the right content type), request/response interceptors, and built-in timeout support.
- XMLHttpRequest is older and harder to use with Promises or modern asynchronous code.
Use Axios if you want advanced features with less setup, and stick with Fetch API if you prefer a lightweight, dependency-free solution.
What happens if a Fetch request fails?
If there’s a network error, the Fetch API will reject the Promise. You can catch it using .catch() or try/catch.
How do you handle errors in the Fetch API?
Check response.ok and response.status to detect HTTP errors, and use try/catch for network failures. You can also log the response body or headers if the server provides error details.
How to fetch images from an API in JavaScript?
Use fetch() to get the image blob, then turn it into a URL:
What is the difference between REST API and Fetch API?
The REST API is the service or data source. The Fetch API is the tool in JavaScript that lets you connect to it and fetch data with network requests.