DEV Community

Cover image for How to Fetch Data from an API using the Fetch API in JavaScript
Oluwadamisi Samuel Praise
Oluwadamisi Samuel Praise

Posted on

How to Fetch Data from an API using the Fetch API in JavaScript

Fetching data from an API (Application Programming Interface) is a common task in web development. It allows you to get data from a server and use it in your web application.
The Fetch API provides a simple and modern way to make HTTP requests in JavaScript. This article will guide you through the basics of using the Fetch API to retrieve data.

Introduction to the Fetch API

The Fetch API is built into modern browsers and provides a way to make network requests similar to XMLHttpRequest (XHR). However, it is more powerful and flexible. It uses Promises, which makes it easier to handle asynchronous operations and avoid callback hell.

Basic Usage

To fetch data from an API, you need to follow these steps:

  • Make a request using the fetch function.
  • Process the response.
  • Handle any errors.

Making a Request

The fetch function takes a URL as an argument and returns a Promise. Here’s a basic example:

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

In this example:

  • fetch('https://api.example.com/data') initiates a GET request to the specified URL.
  • .then(response => response.json()) processes the response and converts it to JSON format.
  • .then(data => console.log(data)) logs the data to the console.
  • .catch(error => console.error('Error:', error)) handles any errors that occur during the fetch operation.

Handling Different Response Types

The Fetch API allows you to handle various response types, including JSON, text, and Blob. Here’s how to handle the different types:

JSON

Most APIs return data in JSON format. You can use the json() method to parse the response:

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

Text

If the API returns plain text, use the text() method:

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

Blob

For binary data, such as images or files, use the blob() method:

fetch('https://api.example.com/image')
    .then(response => response.blob())
    .then(imageBlob => {
        const imageUrl = URL.createObjectURL(imageBlob);
        const img = document.createElement('img');
        img.src = imageUrl;
        document.body.appendChild(img);
    })
    .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Handling HTTP Methods

The Fetch API supports various HTTP methods, including GET, POST, PUT, and DELETE. You can specify the method and other options using an options object.

GET Request

A GET request is the default method. Here's how to make a GET request:

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

POST Request

To send data to the server, use a POST request. Include the method, headers, and body in the options object:

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

PUT Request

A PUT request updates existing data on the server. It’s similar to a POST request:

fetch('https://api.example.com/data/1', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ key: 'updatedValue' })
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

DELETE Request

To delete data from the server, use a DELETE request:

fetch('https://api.example.com/data/1', {
    method: 'DELETE'
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Handling Errors

Errors can occur during a fetch operation due to network issues, server errors, or invalid responses. You can handle these errors using the .catch() method:

fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('There has been a problem with your fetch operation:', error));
Enter fullscreen mode Exit fullscreen mode

In this example, we check if the response is not ok (status code outside the range 200-299) and throw an error if it’s not.

Conclusion

The Fetch API is a powerful and flexible tool for making HTTP requests in JavaScript. It simplifies the process of fetching data from an API and handling different response types. By understanding how to use the Fetch API, you can build more dynamic and responsive web applications. Remember to always handle errors gracefully to ensure a smooth user experience.

Top comments (0)