Fetch API in JavaScript

The Fetch API is a modern JavaScript API used to make HTTP requests in a simpler and more powerful way than its predecessor, XMLHttpRequest. It is built into most modern browsers and provides an easy way to fetch resources from a network, such as JSON data, images, or other files.

1. Basics of Fetch API

The fetch() function is used to make HTTP requests. It returns a Promise that resolves to the response of the request, allowing for asynchronous operations. The response can then be processed using methods like response.json(), response.text(), and others, depending on the type of data returned by the server.

1.1 Simple GET Request

A simple GET request is used to retrieve data from a server. The Fetch API makes this process very straightforward.

Example: Making a simple GET request

          
          fetch('https://jsonplaceholder.typicode.com/posts')
              .then(response => response.json()) // Parse the JSON response
              .then(data => {
                  console.log(data); // Log the data to the console
              })
              .catch(error => console.error('Error fetching data:', error));
          
      

In this example, we fetch a list of posts from jsonplaceholder.typicode.com and log the resulting data (in JSON format) to the console.

1.2 Handling Response Status

After making a request, it's important to check the status of the response. The response.ok property can be used to check if the response was successful (status code 200-299).

Example: Handling response status

          
          fetch('https://jsonplaceholder.typicode.com/posts')
              .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('There was a problem with the fetch operation:', error));
          
      

In this example, if the response is not successful, an error is thrown and logged to the console.

2. Making POST Requests with Fetch API

The Fetch API is not only used for GET requests; it can also be used to send data to a server using the POST method. This is useful when submitting form data, sending JSON, or interacting with a REST API.

Example: Making a POST request

          
          const newPost = {
              title: 'New Post',
              body: 'This is the body of the new post',
              userId: 1
          };

          fetch('https://jsonplaceholder.typicode.com/posts', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json'
              },
              body: JSON.stringify(newPost) // Send the data as a JSON string
          })
          .then(response => response.json()) // Parse the response
          .then(data => console.log('Post created:', data))
          .catch(error => console.error('Error creating post:', error));
          
      

This example demonstrates how to create a new post by sending a JSON object to the server. The Content-Type header is set to application/json, and the body contains the data to be sent, which is stringified using JSON.stringify().

3. Fetch API with Async/Await

The Fetch API can also be used with async/await, making it easier to write asynchronous code in a synchronous style. Using async/await can improve code readability and make it easier to manage errors.

Example: Using async/await with Fetch API

          
          async function fetchData() {
              try {
                  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                  if (!response.ok) {
                      throw new Error('Network response was not ok');
                  }
                  const data = await response.json();
                  console.log(data);
              } catch (error) {
                  console.error('There was a problem with the fetch operation:', error);
              }
          }

          fetchData();
          
      

In this example, we define an async function fetchData that fetches data from the API. The await keyword is used to wait for the response to be resolved, and the data is logged once the request is completed.

4. Working with Query Parameters

Sometimes you need to include query parameters in the URL when making a GET request. This can be done easily by appending parameters to the URL.

Example: Adding query parameters to the URL

          
          const userId = 1;
          fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
              .then(response => response.json())
              .then(data => console.log(data))
              .catch(error => console.error('Error fetching data:', error));
          
      

In this example, we fetch posts by a specific user by including the userId query parameter in the URL.

5. Handling Errors in Fetch API

While using the Fetch API, it's important to handle both network errors (e.g., no internet connection) and response errors (e.g., 404 or 500 errors). You can use catch() to handle these errors gracefully.

Example: Handling errors with Fetch API

          
          fetch('https://jsonplaceholder.typicode.com/invalid-endpoint')
              .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 fetching data:', error));
          
      

In this example, an invalid endpoint is used, which will trigger an error. The catch() method handles the error and logs it to the console.

6. Conclusion

The Fetch API is a powerful and flexible tool for making HTTP requests in JavaScript. It simplifies the process of sending and receiving data asynchronously, and with the help of promises or async/await, it enables cleaner and more readable code. Whether you're working with GET, POST, or other HTTP methods, the Fetch API allows you to interact with APIs and external resources easily, making it an essential tool for modern JavaScript development.





Advertisement