Mapagam
  • JavaScript 
  • Web APIs 
  • TypeScript 
  • React 

How to Use the Fetch API for Beginners

Posted on March 27, 2025 • 5 min read • 1,033 words
Share via
Mapagam
Link copied to clipboard

Learn how to use the Fetch API in JavaScript to make HTTP requests, handle data, and manage errors in this beginner-friendly guide.

On this page
1. What is the Fetch API? 1.1 Introduction to the Fetch API 1.2 Why Use the Fetch API? 2. Basic Syntax of Fetch 2.1 The Fetch Function 2.2 Fetching Data from an API 2.3 Handling Errors 2.4 The Response Object 3. Sending Data with Fetch 3.1 Making a POST Request 3.2 Sending Form Data 3.3 PUT and DELETE Requests 4. Working with Headers 4.1 Understanding Headers 4.2 Custom Headers 5. Handling JSON and Other Data Formats 5.1 Working with JSON 5.2 Working with Text and Other Formats 6. Advanced Features of Fetch 6.1 Handling Timeouts 6.2 Using AbortController to Cancel Requests 7. Conclusion

The Fetch API is a modern JavaScript API that allows you to make HTTP requests, such as retrieving data from a server or sending data to it. As a beginner, using the Fetch API may seem intimidating, but it’s an essential skill for working with web applications that interact with external data.

1. What is the Fetch API?

1.1 Introduction to the Fetch API

The Fetch API provides an easy and efficient way to interact with web servers. It replaces the older XMLHttpRequest, providing a more modern, promise-based interface. Fetch is widely supported in modern browsers and can handle tasks like loading data from a server, sending data to a server, and managing requests and responses.

1.2 Why Use the Fetch API?

  • Promise-based: Fetch returns a promise, which makes it easier to handle asynchronous operations than using callbacks.
  • Readable code: It simplifies working with HTTP requests by allowing for more readable and maintainable code.
  • Wide support: It’s supported by almost all modern browsers.
  • CORS support: Fetch also works well with Cross-Origin Resource Sharing (CORS), making it easier to interact with APIs across different domains.

2. Basic Syntax of Fetch

2.1 The Fetch Function

The basic syntax of a fetch request looks like this:

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
  • url: This is the URL of the resource you want to fetch.
  • options: This is an optional parameter where you can specify method type, headers, body content, and other settings for the request.

2.2 Fetching Data from an API

To get data from an API, you use the fetch() function and handle the response using .then():

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

In this example:

  • The URL 'https://api.example.com/data' is the API endpoint.
  • The response.json() method converts the response to a JavaScript object.
  • .catch() catches any errors that occur during the fetch operation.

2.3 Handling Errors

It’s important to handle errors while making HTTP requests. Fetch won’t reject an HTTP error status (like 404 or 500); instead, it will resolve the promise. That’s why you need to manually check the response.ok property to verify if the request was successful.

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

2.4 The Response Object

When a fetch request completes successfully, it returns a Response object. This object contains:

  • status: The HTTP status code of the response (e.g., 200, 404).
  • ok: A boolean indicating whether the response status is in the range 200–299.
  • json(): A method to parse the response body as JSON.
  • text(): A method to parse the response body as text.

3. Sending Data with Fetch

3.1 Making a POST Request

To send data to the server, you need to make a POST request. Here’s an example:

const data = {
  username: 'user1',
  password: 'password123'
};

fetch('https://api.example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

In this example:

  • method: Set to 'POST' to send data to the server.
  • headers: Specifies that the content being sent is in JSON format.
  • body: Contains the data being sent. It’s converted to a JSON string using JSON.stringify().

3.2 Sending Form Data

If you need to send form data, you can use FormData:

const formData = new FormData();
formData.append('username', 'user1');
formData.append('password', 'password123');

fetch('https://api.example.com/login', {
  method: 'POST',
  body: formData
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

3.3 PUT and DELETE Requests

In addition to GET and POST, you can make other types of HTTP requests, such as PUT and DELETE.

PUT Request

A PUT request is used to update data on the server.

fetch('https://api.example.com/user/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'updatedUser',
    email: 'updated@example.com'
  })
})
  .then(response => response.json())
  .then(data => console.log('Updated:', data))
  .catch(error => console.error('Error:', error));

DELETE Request

A DELETE request is used to delete data on the server.

fetch('https://api.example.com/user/1', {
  method: 'DELETE'
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Failed to delete');
    }
    return response.json();
  })
  .then(data => console.log('Deleted:', data))
  .catch(error => console.error('Error:', error));

4. Working with Headers

4.1 Understanding Headers

Headers are used to provide metadata about the request or response, such as content type or authentication details. In Fetch, you can modify headers with the headers option.

Example:

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer your-token-here',
    'Accept': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

4.2 Custom Headers

You can also set custom headers as needed:

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Custom-Header': 'custom-value'
  },
  body: JSON.stringify({ key: 'value' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

5. Handling JSON and Other Data Formats

5.1 Working with JSON

When interacting with most APIs, data is exchanged in JSON format. Use response.json() to parse the response as JSON:

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

5.2 Working with Text and Other Formats

If you need to handle other formats, like plain text or Blob (binary data), use methods like response.text() or response.blob().

For plain text:

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

6. Advanced Features of Fetch

6.1 Handling Timeouts

Fetch doesn’t support timeouts natively, but you can implement one manually using Promise.race(). Here’s how you can handle timeouts:

const fetchWithTimeout = (url, options, timeout = 5000) => {
  const timeoutPromise = new Promise((_, reject) =>
    setTimeout(() => reject('Request timed out'), timeout)
  );

  const fetchPromise = fetch(url, options);

  return Promise.race([fetchPromise, timeoutPromise]);
};

fetchWithTimeout('https://api.example.com/data', { method: 'GET' })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

6.2 Using AbortController to Cancel Requests

You can cancel a request by using the AbortController API:

const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Error:', error);
    }
  });

// To abort the fetch request
controller.abort();

7. Conclusion

The Fetch API is a powerful tool for making HTTP requests in JavaScript. It provides a cleaner, promise-based approach to fetching and sending data to web servers, replacing the older XMLHttpRequest.

Fetch Api   JavaScript   HTTP Requests   Web Development   API Tutorial  
Fetch Api   JavaScript   HTTP Requests   Web Development   API Tutorial  
 JavaScript DOM API Explained Simply
What Are JavaScript Web APIs? A Beginner’s Guide 

More Reading!

  1. How to Use the Geolocation API in JavaScript (With Live Demo)
  2. How TypeScript’s Type Inference Works (And Why It’s a Game-Changer)
  3. Understanding the JavaScript Clipboard API for Seamless Copy-Paste
  4. Beginner’s Guide to the JavaScript DOM API (With Practical Examples)
  5. Using the History API for Simple Navigation in JavaScript
On this page:
1. What is the Fetch API? 1.1 Introduction to the Fetch API 1.2 Why Use the Fetch API? 2. Basic Syntax of Fetch 2.1 The Fetch Function 2.2 Fetching Data from an API 2.3 Handling Errors 2.4 The Response Object 3. Sending Data with Fetch 3.1 Making a POST Request 3.2 Sending Form Data 3.3 PUT and DELETE Requests 4. Working with Headers 4.1 Understanding Headers 4.2 Custom Headers 5. Handling JSON and Other Data Formats 5.1 Working with JSON 5.2 Working with Text and Other Formats 6. Advanced Features of Fetch 6.1 Handling Timeouts 6.2 Using AbortController to Cancel Requests 7. Conclusion
Follow me

I work on everything coding and technology

   
Mapagam
Mapagam is your go-to resource for all things related to frontend development. From the latest frameworks and libraries to tips, tutorials, and best practices, we dive deep into the ever-evolving world of web technologies.
Licensed under Creative Commons (CC BY-NC-SA 4.0).
 
Frontend
JavaScript 
Web Api 
TypeScript 
React 
Social
Linkedin 
Github 
Mapagam
Code copied to clipboard