Back to JavaScript
2026-03-067 min read

JavaScript Fetch API

Learn JavaScript Fetch API step by step with clear examples and exercises.

Why This Matters

Welcome to our full guide on the JavaScript Fetch API! In today's dynamic web landscape, this powerful tool is indispensable for making HTTP requests directly from your JavaScript code, enabling you to interact with APIs, servers, and data sources seamlessly. Whether you're preparing for an interview, tackling a real-world project, or debugging a complex issue, our guide will provide practical insights and walkthroughs that set it apart from other resources.

Why This Matters

The Fetch API is essential for modern web development due to its ability to simplify the process of making HTTP requests, allowing you to create dynamic web applications, enhance user experiences, and streamline data management. It's a crucial skill for any front-end developer aiming to build interactive and responsive web pages.

Prerequisites

Before diving into the Fetch API, ensure you have a good understanding of:

  1. JavaScript: Basic knowledge of variables, functions, loops, control structures, and ES6 features is necessary to follow along.
  2. HTML/DOM Manipulation: Understanding how to manipulate the Document Object Model (DOM) will help you integrate Fetch API results into your web pages.
  3. Promises: The Fetch API relies on Promises for handling asynchronous operations, so familiarity with this concept is crucial.
  4. ES6 Syntax and Features: Understanding ES6 syntax and features such as arrow functions, template literals, and destructuring assignments will make it easier to work with the Fetch API.

Core Concept

The JavaScript Fetch API is a built-in browser function that allows you to send HTTP requests from JavaScript and receive responses in the form of Promises. This powerful tool simplifies asynchronous communication between your web application and external resources, such as APIs, servers, or data sources. Here's a basic example:

fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Do something with the data
})
.catch(error => console.log(error));

In this example, we're making a GET request to https://api.example.com/data, expecting JSON data in response. The fetch() function returns a Promise that resolves with the Response object, which contains information about the HTTP response (headers, status code, etc.). We then use another .then() to parse the response as JSON and perform an action with the resulting data.

Request Methods

The Fetch API supports various request methods such as GET, POST, PUT, DELETE, and more. Each method corresponds to a specific HTTP verb (e.g., GET for retrieving resources, POST for creating new ones).

fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key1: 'value1', key2: 'value2' })
})
.then(response => response.json())
.then(data => {
// Do something with the data
});

In this example, we're making a POST request to https://api.example.com/data, sending JSON data in the body of the request.

Worked Example

Let's build a simple weather app using the OpenWeatherMap API. First, sign up for a free API key at OpenWeatherMap.

const apiKey = 'YOUR_API_KEY';
const cityInput = document.getElementById('city');
const weatherDiv = document.getElementById('weather');

document.getElementById('getWeather').addEventListener('click', () => {
const city = cityInput.value;
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
const temp = data.main.temp - 273.15; // Convert Kelvin to Celsius
const description = data.weather[0].description;
weatherDiv.innerHTML = `Temperature: ${temp.toFixed(2)}°C<br>Description: ${description}`;
})
.catch(error => console.log(error));
});

In this example, we're fetching the current weather data for a given city when the "Get Weather" button is clicked. The fetched JSON data is then used to display the temperature and weather description in the weatherDiv.

Common Mistakes

  1. Forgetting to parse responses: Always ensure you're parsing responses correctly based on their content type (JSON, text, etc.).
  2. Ignoring CORS issues: Cross-Origin Resource Sharing (CORS) errors can prevent your requests from being fulfilled. Make sure the API you're using supports CORS or consider using a proxy server.
  3. Misusing fetch() with AJAX: While fetch() is an improvement over traditional XMLHttpRequest (XHR), it still shares some limitations, such as not supporting IE10 and earlier versions. Be aware of your target audience when deciding which method to use.
  4. Not handling errors properly: Always include a .catch() block to handle potential errors gracefully.
  5. Incorrectly setting request headers: Ensure you set the appropriate headers for your requests, such as Content-Type for POST and PUT requests.
  6. Not checking response status codes: Always check the response status code (e.g., 200 OK) to ensure the request was successful.
  7. Ignoring timeouts: Consider setting a timeout on long-running requests to prevent hanging or unresponsive applications.

Common Mistakes - Subheadings

  1. Forgetting to parse responses
  • Always ensure you're parsing responses correctly based on their content type (JSON, text, etc.).
  1. Ignoring CORS issues
  • Cross-Origin Resource Sharing (CORS) errors can prevent your requests from being fulfilled.
  • Make sure the API you're using supports CORS or consider using a proxy server.
  1. Misusing fetch() with AJAX
  • While fetch() is an improvement over traditional XMLHttpRequest (XHR), it still shares some limitations, such as not supporting IE10 and earlier versions.
  1. Not handling errors properly
  • Always include a .catch() block to handle potential errors gracefully.
  1. Incorrectly setting request headers
  • Ensure you set the appropriate headers for your requests, such as Content-Type for POST and PUT requests.
  1. Not checking response status codes
  • Always check the response status code (e.g., 200 OK) to ensure the request was successful.
  1. Ignoring timeouts
  • Consider setting a timeout on long-running requests to prevent hanging or unresponsive applications.

Practice Questions

  1. How can you send a POST request using the Fetch API?
  • Create a new Promise using fetch() and set the method to 'POST'. Include any necessary headers and body data, then parse the response as needed.
  1. What should you do if you encounter a CORS error while making an HTTP request with Fetch API?
  • Make sure the API you're using supports CORS or consider using a proxy server to bypass the issue.
  1. Explain how Promises are used in the Fetch API.
  • The Fetch API returns a Promise that resolves with the Response object, which contains information about the HTTP response (headers, status code, etc.). You can use .then() and .catch() to handle the resolved value or any errors that occur during the request.
  1. Write code to fetch JSON data from an API and display it on your web page using JavaScript.
  • Use fetch() to send a GET request to the desired API endpoint, then parse the response as JSON and manipulate the DOM to display the data.
  1. What happens if a fetch() call fails?
  • If a fetch() call fails (e.g., due to network errors, invalid URLs, or unsupported HTTP methods), it will return a rejected Promise with an error object containing details about the failure.
  1. How can you set a timeout on a Fetch API request?
  • Use the fetch() function's second argument to pass an options object that includes a timeout property specifying the number of milliseconds before the request times out.
  1. What is the difference between fetch() and XMLHttpRequest (XHR)?
  • Fetch API is a more modern, flexible, and easier-to-use approach for making HTTP requests compared to XHR. It offers better support for Promises, asynchronous operations, and modern browser features. However, XHR may still be necessary for older browsers that do not support the Fetch API.

FAQ

  1. Why should I use the Fetch API instead of XMLHttpRequest (XHR)?
  • The Fetch API offers a more modern, flexible, and easier-to-use approach for making HTTP requests compared to XHR. It also supports Promises out of the box, making asynchronous operations simpler.
  1. How can I handle CORS issues with the Fetch API?
  • You can use a proxy server or create a simple backend service on your own server to bypass CORS restrictions. Alternatively, some APIs support CORS headers that allow requests from specific domains.
  1. What happens if a fetch() call fails?
  • If a fetch() call fails (e.g., due to network errors, invalid URLs, or unsupported HTTP methods), it will return a rejected Promise with an error object containing details about the failure.
  1. How can I set a timeout on a Fetch API request?
  • Use the fetch() function's second argument to pass an options object that includes a timeout property specifying the number of milliseconds before the request times out.
  1. What is the difference between fetch() and XMLHttpRequest (XHR)?
  • Fetch API is a more modern, flexible, and easier-to-use approach for making HTTP requests compared to XHR. It offers better support for Promises, asynchronous operations, and modern browser features. However, XHR may still be necessary for older browsers that do not support the Fetch API.
JavaScript Fetch API | JavaScript | XQA Learn