Fetch API in JavaScript (original) (raw)

Last Updated : 14 Feb, 2025

The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.

**Syntax

fetch(url, options) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

How Fetch API Works?

Common HTTP Request Methods in Fetch API

Basic Fetch Request

A simple GET request to fetch data from an API.

JavaScript `

fetch('https://fakestoreapi.com/products/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

`

**Output

Screenshot-2025-01-23-124520

Making a Basic GET Request

Handling Response Status Codes

When making an HTTP request, handling response status codes is crucial for determining whether the request was successful or if there was an error. The status code provides information about the result of the request.

JavaScript `

fetch('https://api.example.com/data') .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Network response was not ok'); } }) .then(data => console.log(data)) .catch(error => console.error('There was a problem with the fetch operation:', error));

`

**Output

Screenshot-2025-02-13-110223

Handling Response Status Codes

Using async/await with Fetch API

Using async/await makes handling asynchronous code like fetch cleaner and more readable. It allows you to write code that appears synchronous while still being non-blocking.

JavaScript `

async function getP() { try { const response = await fetch('https://fakestoreapi.com/products'); if (response.ok) { const data = await response.json(); console.log(data); } else { throw new Error('Failed to fetch data'); } } catch (error) { console.error('Error:', error); } } getP()

`

**Output

Screenshot-2025-02-13-111336

Using async/await with Fetch API

Sending Custom Headers with Fetch API

Sending custom headers with the Fetch API allows you to include additional information with your request, like authentication tokens or content types.

JavaScript ``

//server.js const express = require('express'); const app = express();

app.use(express.json()); // Middleware to parse JSON request body

app.post('/test-api', (req, res) => { console.log('Received Headers:', req.headers); console.log('Received Body:', req.body);

res.json({ message: 'Headers received successfully!', receivedHeaders: req.headers });

});

const PORT = 3000; app.listen(PORT, () => { console.log(Server running on http://localhost:${PORT}); });

`` JavaScript `

//client.js fetch('http://localhost:3000/test-api', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer my-secret-token', 'Custom-Header': 'HelloWorld' }, body: JSON.stringify({ message: 'Hello API!' }) }) .then(response => response.json()) .then(data => console.log('Response:', data)) .catch(error => console.error('Error:', error));

`

Screenshot-2025-02-13-121558

Sending Custom Headers with Fetch API

Handling Different Request Methods (POST, PUT, DELETE)

1. GET Request to Retrieve Data

Fetching a list of items from an API.

JavaScript `

fetch('https://fakestoreapi.com/products/1') .then(response => response.json()) .then(items => console.log(items));

`

Screenshot-2025-01-23-125201

GET Request to Retrieve Data

2. POST Request to Submit Data

Sending data to an API using POST.

JavaScript `

const data = { name: 'Pranjal', age: 25 }; fetch('https://fakestoreapi.com/products', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => console.log(result));

`

Screenshot-2025-01-23-130059

POST Request to submit data

3. PUT Request to Update Data

Updating existing user information.

JavaScript `

const updatedData = { id: 1, price: 300 };

fetch('https://fakestoreapi.com/products/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updatedData) }) .then(response => response.json()) .then(result => console.log(result));

`

Screenshot-2025-01-23-152657

PUT Request to Update Data

4. DELETE Request to Remove Data

Deleting a user from an API.

JavaScript `

fetch('https://fakestoreapi.com/products/1', { method: 'DELETE' }) .then(response => response.json()) .then(result => console.log('Deleted:', result));

`

Screenshot-2025-01-23-153110

DELETE Request to Remove Data

Handling Errors in Fetch API

When making requests with fetch(), errors can occur due to network issues or invalid responses. Proper error handling ensures a smooth user experience.

JavaScript ``

fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error(HTTP error! Status: ${response.status}); } return response.json(); }) .then(data => console.log('Data:', data)) .catch(error => console.error('Fetch error:', error.message));

``

Screenshot-2025-02-13-123229

Handling Errors in Fetch API

Conclusion

The Fetch API is a powerful tool for making HTTP requests in JavaScript. It simplifies working with asynchronous data and provides flexibility in handling various request types.

**Key Takeaways