How to Use Fetch API in JavaScript

A minimalist, abstract representation of the process of using the Fetch API in JavaScript. The image should incorporate abstract symbols to represent code, like curly braces and semi-colons, as well as symbolic representations of data transfer, such as arrows or lines connecting boxes. In the center, a large, stylized cursor should hint towards programming activity. The palette should consist of warm and inviting shades of orange and yellow. Ensure no text, people, brand names, or logos are present in the image.

Introduction to Fetch API in JavaScript

The Fetch API in JavaScript provides an easy and efficient way to make HTTP requests to servers, allowing you to retrieve and send data.

If you are dealing with data from an API or a server, using the Fetch API becomes essential.

It replaces the older XMLHttpRequest (XHR) method and is much simpler to implement.

TLDR: How to Use Fetch API in JavaScript

You can use the Fetch API by calling fetch() with a URL and then working with the returned promise:


// Basic usage with Fetch API
fetch('https://api.example.com/data') // URL of the API endpoint
.then(response => response.json()) // Parse the JSON from the response
.then(data => console.log(data)) // Handle the data
.catch(error => console.error('Error:', error)); // Handle errors

Understanding the Fetch API

The Fetch API provides a global fetch function that allows you to make network requests similar to XHR but with a more powerful and flexible feature set.

It is built into modern browsers, so you do not need to import any additional libraries.

Fetch uses Promises, which enables it to process asynchronous requests in a more concise and readable manner.

Sending a Basic GET Request

To make a basic GET request, you can use the following code snippet:


// Making a basic GET request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json()) // Convert the response to JSON
.then(data => console.log(data)) // Log the data to the console
.catch(error => console.error('Error:', error)); // Catch and log errors

This code fetches data from the given URL and logs it to the console.

The fetch function returns a Promise that resolves to the Response object representing the entire HTTP response.

Handling Different Response Types

When you make a request, you might receive data in different formats such as JSON, text, blob, or form-data.

Here is how you can handle various response types:


// Handling JSON response
fetch('https://api.example.com/data')
.then(response => response.json()) // Parsing JSON
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// Handling text response
fetch('https://api.example.com/text')
.then(response => response.text()) // Parsing text
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// Handling Blob response
fetch('https://api.example.com/image')
.then(response => response.blob()) // Parsing Blob
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Working with POST Requests

To send data to a server, you often need to use a POST request.

Here is how you can send a POST request using the Fetch API:


// Sending a POST request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // HTTP method
headers: {
'Content-Type': 'application/json', // Setting the request headers
},
body: JSON.stringify({
title: 'foo', // Data to be sent
body: 'bar',
userId: 1
}),
})
.then(response => response.json()) // Parsing JSON from the response
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors

This code snippet sends a POST request with JSON data to the given URL.

The method property is set to ‘POST’, and the body contains the data to be sent in a JSON string format.

Using Async/Await for Fetch

Using async/await syntax can make your code look cleaner and more readable.

Here is an example of how you can use async/await with Fetch API:


// Using async/await with Fetch API
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
console.log(data); // Handle the parsed data
} catch (error) {
console.error('Error:', error); // Handle errors
}
}

fetchData();

The async keyword is used to define an asynchronous function.

The await keyword pauses the execution until the Promise is resolved.

Handling Errors with Fetch

Handling errors is crucial when making network requests.

Fetch does not reject the Promise if the HTTP status is an error like 404 or 500.

You have to manually check if the response is successful and then handle the error.


// Handling errors in Fetch API
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) { // Check if the request was successful
throw new Error('Network response was not ok');
}
return response.json(); // Parse JSON if successful
})
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Fetch error:', error)); // Handling errors

The code checks if the response is ok (status in the range 200-299).

If not, it throws an error that is caught by the catch method.

Setting Request Headers

Sometimes you need to set custom headers in your request for authentication or content type.

Here is how to set headers using the Fetch API:


// Setting custom headers in Fetch API
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer your-token', // Authentication token
'Content-Type': 'application/json' // Content type
}
})
.then(response => response.json()) // Parsing JSON from the response
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors

The headers option lets you add custom headers to your request.

This can be useful for authentication and specifying content types.

Working with Query Parameters

To send query parameters in your Fetch request, you can append them to the URL.

Here is how:


// Sending query parameters with Fetch API
const params = new URLSearchParams({
userId: 1,
id: 2
});

fetch(`https://jsonplaceholder.typicode.com/posts?${params}`)
.then(response => response.json()) // Parsing JSON from the response
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors

The above code constructs a query string using URLSearchParams and appends it to the URL.

This can be very useful for filtering or searching data on the server.

FAQs

What is the Fetch API?

The Fetch API is a modern interface for making network requests similar to XMLHttpRequest but with a more powerful and flexible feature set.

How do I handle errors with Fetch?

You need to check if the response is successful using the ok property and throw an error if it is not.

Can I use Fetch for PUT and DELETE requests?

Yes, you need to use the method property in the options object and set it to ‘PUT’ or ‘DELETE’.

Is Fetch supported in all browsers?

Fetch is supported in all modern browsers but not in Internet Explorer.

How can I cancel a Fetch request?

You can use the AbortController to cancel a Fetch request.

Can I send JSON with Fetch?

Yes, you need to set the Content-Type header to ‘application/json’ and stringify your JSON data.

How do I include credentials with Fetch?

You can include credentials by setting the credentials option to ‘include’ in your Fetch request.

Introduction to the Fetch API in JavaScript

The Fetch API in JavaScript offers a modern, flexible way to make HTTP requests, replacing the older XMLHttpRequest (XHR).

It’s crucial for anyone dealing with data from APIs or servers, providing a simpler, promise-based syntax.

Using Fetch allows greater readability and cleaner code, making your projects more maintainable.

TLDR: Making HTTP Requests with Fetch API in JavaScript

To use the Fetch API, you call fetch() with a URL. Then, handle the resulting promise to work with the data:


// Basic usage with Fetch API
fetch('https://api.example.com/data') // URL of the API endpoint
.then(response => response.json()) // Parse the JSON from the response
.then(data => console.log(data)) // Handle the data
.catch(error => console.error('Error:', error)); // Handle errors

Understanding the Fetch API

The Fetch API provides a global fetch function that allows you to make network requests in a way similar to XHR but with more features.

It comes built into modern browsers, so no additional libraries are needed.

By using Promises, Fetch makes handling asynchronous requests simpler and more readable.

Sending a Basic GET Request

To make a basic GET request using the Fetch API, follow this code snippet:


// Making a basic GET request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json()) // Convert the response to JSON
.then(data => console.log(data)) // Log the data to the console
.catch(error => console.error('Error:', error)); // Catch and log errors

This code fetches data from a given URL and logs it to the console.

The fetch function returns a Promise that resolves to the Response object representing the entire HTTP response.

Handling Different Response Types

The Fetch API allows you to handle different response types, such as JSON, text, and blobs.

Here is how you manage various response types:


// Handling JSON response
fetch('https://api.example.com/data')
.then(response => response.json()) // Parsing JSON
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// Handling text response
fetch('https://api.example.com/text')
.then(response => response.text()) // Parsing text
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// Handling Blob response
fetch('https://api.example.com/image')
.then(response => response.blob()) // Parsing Blob
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Sending a POST Request

To send data to a server, you’ll often use a POST request.

Here is how you can send a POST request using the Fetch API:


// Sending a POST request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // HTTP method
headers: {
'Content-Type': 'application/json', // Setting the request headers
},
body: JSON.stringify({
title: 'foo', // Data to be sent
body: 'bar',
userId: 1
}),
})
.then(response => response.json()) // Parsing JSON from the response
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors

This code sends a POST request with JSON data to a given URL.

The method property is set to ‘POST’, and the body contains the data to be sent in a JSON string format.

Using Async/Await Syntax with Fetch

Using async/await syntax makes your code look cleaner and more readable.

Here is an example of how you can use async/await with Fetch API:


// Using async/await with Fetch API
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
console.log(data); // Handle the parsed data
} catch (error) {
console.error('Error:', error); // Handle errors
}
}

fetchData();

The async keyword is used to define an asynchronous function.

The await keyword pauses the execution until the Promise is resolved.

Handling Errors in Fetch

Error handling is crucial when making network requests.

Fetch does not reject the Promise for HTTP errors like 404 or 500. You need to manually check if the response is successful.


// Handling errors in Fetch API
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) { // Check if the request was successful
throw new Error('Network response was not ok');
}
return response.json(); // Parse JSON if successful
})
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Fetch error:', error)); // Handling errors

The code checks if the response is ok (status in the range 200-299).

If it is not, it throws an error that is caught by the catch method.

Setting Request Headers

There are times when you need to set custom headers in your request for tasks like authentication or specifying content types.

Here is how to set headers using the Fetch API:


// Setting custom headers in Fetch API
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer your-token', // Authentication token
'Content-Type': 'application/json' // Content type
}
})
.then(response => response.json()) // Parsing JSON from the response
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors

The headers option lets you add custom headers to your request.

This can be very useful for tasks like authentication and specifying content types.

Sending Query Parameters

To send query parameters in your Fetch request, append them to the URL.

Here’s how to do it:


// Sending query parameters with Fetch API
const params = new URLSearchParams({
userId: 1,
id: 2
});

fetch(`https://jsonplaceholder.typicode.com/posts?${params}`)
.then(response => response.json()) // Parsing JSON from the response
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors

The above code constructs a query string using URLSearchParams and appends it to the URL.

This approach is useful for filtering or searching data on the server.

FAQs

What is the Fetch API?

The Fetch API is a modern interface for making network requests similar to XMLHttpRequest but more powerful.

How do I handle errors with Fetch?

Check if the response is successful using the ok property and throw an error if it isn’t.

Can I use Fetch for PUT and DELETE requests?

Yes, you can. Simply use the method property in the options object and set it to ‘PUT’ or ‘DELETE’.

Is Fetch supported in all browsers?

Fetch is supported in all modern browsers except Internet Explorer.

How can I cancel a Fetch request?

You can use the AbortController to cancel a Fetch request.

Can I send JSON with Fetch?

Yes, you need to set the Content-Type header to ‘application/json’ and stringify your JSON data.

How do I include credentials with Fetch?

You can include credentials by setting the credentials option to ‘include’ in your Fetch request.

Shop more on Amazon