DEV Community

Harsh Mishra
Harsh Mishra

Posted on

Fetch API Full Guide

Introduction to Fetch API

The Fetch API is a modern, native JavaScript API that allows you to make HTTP requests in a simple and flexible way. It provides an easier and cleaner alternative to older technologies like XMLHttpRequest. Fetch is promise-based, which means it works well with modern JavaScript features such as async/await and .then() chaining.

The Fetch API provides an easy-to-understand way of interacting with RESTful APIs, handling both simple and complex requests. It is widely supported in modern browsers and is a common tool used for web development.

Key Features of Fetch API:

  1. Promise-based: Built on Promises, providing an easy and intuitive way to manage asynchronous code.
  2. Supports all HTTP methods: GET, POST, PUT, DELETE, PATCH, etc.
  3. No callback hell: Thanks to Promises, it avoids nested callbacks.
  4. Stream support: Fetch supports streams, which makes it suitable for handling large amounts of data efficiently.
  5. Improved error handling: Unlike XMLHttpRequest, the Fetch API will not reject an HTTP error status (e.g., 404 or 500). You have to handle these manually.

Installation

The Fetch API is built into modern web browsers, meaning you don’t need to install anything if you’re working in a browser environment. It’s natively available and ready to use for making HTTP requests.

However, if you’re working in a Node.js environment (where fetch is not natively supported), you can install a polyfill such as node-fetch.

1. Using npm (For Node.js environment):

If you’re working in a Node.js environment and need to use Fetch, you can install node-fetch:

npm install node-fetch
Enter fullscreen mode Exit fullscreen mode

Then, import it into your project:

const fetch = require('node-fetch');
Enter fullscreen mode Exit fullscreen mode

Using the Fetch API

The Fetch API provides a global fetch() function that you can use to make HTTP requests. This function returns a Promise that resolves to the Response object representing the response to the request.

Syntax

fetch(url, [options])
Enter fullscreen mode Exit fullscreen mode

Parameters

  1. url:

    • Type: string
    • Description: The URL to which the request is sent. This can be a full URL or a relative URL based on the base URL defined in the request.
  2. options (optional):

    • Type: object
    • Description: An optional configuration object to modify the request. Some common options include:
      • method: The HTTP method (e.g., GET, POST, PUT, DELETE).
      • headers: Custom headers to include in the request (e.g., Content-Type, Authorization).
      • body: The request body (only for methods like POST or PUT).
      • mode: Controls cross-origin requests. (e.g., 'cors', 'no-cors', 'same-origin').
      • cache: Specifies how the request will interact with the cache (e.g., 'no-store', 'reload').
      • credentials: Controls cookies and authentication (e.g., 'same-origin', 'include').

Basic Fetch Request (GET)

A basic GET request with the Fetch API is straightforward. The fetch() function makes a request to the provided URL and returns a Promise that resolves with the Response object.

Example Code:

Here’s an example of a simple GET request using the Fetch API:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())  // Parse the JSON from the response
  .then(data => {
    console.log(data);  // Logs the fetched data
  })
  .catch(error => {
    console.error('Error:', error);  // Logs errors if the request fails
  });
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • fetch() initiates the request to the given URL.
  • .then(response => response.json()): Converts the Response object into a JavaScript object by parsing the JSON data.
  • .catch(): Catches and logs any errors, such as network errors or failed requests.

Making POST Requests with Fetch

The Fetch API also allows you to make POST requests. POST requests are typically used for sending data to a server, like submitting a form or creating a new resource.

Syntax for POST Request:

fetch(url, {
  method: 'POST',  // Specifies the HTTP method
  headers: {       // Headers for the request
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)  // Request body with data (must be stringified)
})
Enter fullscreen mode Exit fullscreen mode

Example Code:

Here’s an example of a POST request that sends data to the server:

const postData = {
  title: 'foo',
  body: 'bar',
  userId: 1
};

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'  // Sending JSON data
  },
  body: JSON.stringify(postData)  // Convert JavaScript object to JSON string
})
  .then(response => response.json())  // Parse the response as JSON
  .then(data => {
    console.log('Post Created:', data);  // Logs the created post data
  })
  .catch(error => {
    console.error('Error:', error);  // Logs errors if the request fails
  });
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • method: 'POST': Specifies that this is a POST request.
  • body: JSON.stringify(postData): Converts the data to a JSON string before sending it in the request body.
  • headers: Sets the Content-Type header to application/json to indicate that the data being sent is in JSON format.

Handling Response Data

The Response object returned by the Fetch API contains several properties and methods for interacting with the response data.

Key Properties and Methods of Response:

  1. response.json(): Parses the response body as JSON.
  2. response.text(): Parses the response body as a string.
  3. response.blob(): Parses the response as a binary large object (useful for handling images or files).
  4. response.ok: A boolean indicating if the response status code is in the range 200-299 (successful).
  5. response.status: The HTTP status code of the response (e.g., 200 for success, 404 for not found).
  6. response.headers: The headers returned by the server in response to the request.

Example Code:

Here’s an example of how to handle different types of response data:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();  // Parse response body as JSON
  })
  .then(data => {
    console.log(data);  // Logs the post data (JavaScript object)
  })
  .catch(error => {
    console.error('Error:', error);  // Handles network errors or response parsing errors
  });
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • response.ok checks if the response was successful (status code 200-299). If not, an error is thrown.
  • response.json() is called to parse the response as a JavaScript object.

Handling Errors in Fetch

Unlike XMLHttpRequest, the Fetch API does not automatically reject an HTTP error status (e.g., 404 or 500). It only rejects if there’s a network failure or if the request is blocked. To handle errors like 404 or 500, you’ll need to check the response.ok property.

Error Handling Example:

Here’s an example of how to handle errors effectively in Fetch:

fetch('https://jsonplaceholder.typicode.com/posts/100')  // Non-existent post
  .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('Request failed', error);  // Handles network and HTTP errors
  });
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • response.ok: This checks if the response status code is in the 200–299 range (indicating success).
  • If the request fails (e.g., 404 or 500 error), it will throw an error with the corresponding status code.

Conclusion

The Fetch API is a powerful and modern tool for making HTTP requests in JavaScript. It provides a clean and intuitive way to work with REST APIs, and its promise-based architecture makes it easy to manage asynchronous code. With its support for all HTTP methods, error handling, and response parsing, Fetch is an essential tool for web developers.

Whether you're fetching data, submitting forms, or handling authentication, the Fetch API offers flexibility and control over your HTTP requests, making it an excellent choice for modern web applications.

Top comments (0)