codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🌐

JavaScript

63 / 65 topics
57JavaScript DOM Introduction58JavaScript Selecting DOM Elements59JavaScript Changing HTML & CSS60JavaScript Events61JavaScript addEventListener62JavaScript and JSON63JavaScript Fetch API64JavaScript Local Storage65JavaScript Regular Expressions
Tutorials/JavaScript/JavaScript Fetch API
🌐JavaScript

JavaScript Fetch API

Updated 2026-04-20
3 min read

JavaScript Fetch API

The Fetch API is a modern, powerful interface for making network requests from web browsers. It provides a global fetch() method that allows you to perform HTTP requests to servers and retrieve data asynchronously. This tutorial will cover the basics of using the Fetch API, including how to make GET and POST requests, handle responses, manage errors, and apply best practices.

Introduction

The Fetch API is built on top of Promises, making it easier to write asynchronous code compared to older methods like XMLHttpRequest. It supports all modern browsers and provides a more flexible and powerful way to interact with web resources.

Key Features

  • Promises: Simplifies handling asynchronous operations.
  • Interceptable Requests and Responses: Allows for customization of requests and responses.
  • Supports Streams: Enables processing large data chunks efficiently.
  • Built-in JSON Handling: Automatically parses JSON responses.

Basic Usage

To use the Fetch API, you simply call the fetch() function with a URL. This function returns a Promise that resolves to the Response object representing the response of the request.

Making a GET Request

// Example: Fetching data from an API
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json(); // Parse JSON response into native JavaScript objects
  })
  .then(data => {
    console.log(data); // Handle the data received from the server
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

Making a POST Request

// Example: Sending data to an API
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' }) // Convert JavaScript object to JSON string
})
.then(response => response.json())
.then(data => {
  console.log(data); // Handle the response data
})
.catch(error => {
  console.error('Error:', error);
});

Handling Responses

The Response object provides several methods and properties to handle the server's response:

  • response.ok: A boolean indicating whether the request was successful (status in the range 200–299).
  • response.status: The status code of the response.
  • response.statusText: The status message corresponding to the status code.
  • response.headers: Contains the headers of the response.
  • response.json(): Parses JSON body of the response and returns a Promise that resolves with the result.

Example: Checking Response Status

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);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

Handling Errors

Errors can occur due to network issues, invalid URLs, or server errors. It's important to handle these gracefully.

Example: Error Handling with Try...Catch (Async/Await)

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

fetchData();

Best Practices

  1. Use Async/Await: It makes the code cleaner and easier to read.
  2. Check Response Status: Always validate the response status before processing data.
  3. Handle Errors Gracefully: Provide user feedback or alternative actions when errors occur.
  4. Set Appropriate Headers: Ensure correct content types for requests and responses.

Example: Using Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

fetchData();

Advanced Usage

Using Streams for Large Data

For large files or streams, you can use the ReadableStream interface to process data as it arrives.

fetch('https://api.example.com/largefile')
  .then(response => response.body.getReader())
  .then(reader => {
    const decoder = new TextDecoder();
    let done;
    let chunk;

    (function read() {
      reader.read().then(({ value, done: readingDone }) => {
        if (readingDone) {
          console.log('Stream complete');
          return;
        }
        chunk = decoder.decode(value);
        console.log(chunk);
        read();
      });
    })();
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

Custom Headers and Options

You can customize requests by setting headers, credentials, and other options.

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    'Custom-Header': 'Value'
  },
  credentials: 'include' // Include cookies with the request
})
.then(response => response.json())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error('Fetch error:', error);
});

Conclusion

The Fetch API is a versatile and powerful tool for making network requests in JavaScript. By understanding how to use it effectively, you can build robust web applications that interact with external resources efficiently. Whether you're fetching data from APIs or uploading files, the Fetch API provides the flexibility and control needed to handle these tasks seamlessly.

Remember to always check response statuses, handle errors gracefully, and use best practices to ensure your application is both efficient and reliable.


PreviousJavaScript and JSONNext JavaScript Local Storage

Recommended Gear

JavaScript and JSONJavaScript Local Storage