DEV Community

Cover image for FETCH Requests for Beginners
Alexis Boucouvalas
Alexis Boucouvalas

Posted on • Updated on

FETCH Requests for Beginners

Introduction

Being able to communicate with servers is a crucial aspect to web
development. As developers, we need to be able to retrieve and
submit data, get real time updates, implement authentication and
security, integrate APIs, and much more. We can do all of these
things with the help of the FETCH API given to us by JavaScript.

Understanding FETCH Requests

A FETCH request is a way to fetch resources like data or files
from a server using JavaScript. FETCH enables you to make HTTP
requests and handles the response in a streamlined manner.

FETCH requests even offer a range of features that make
developers' lives easier. We have:

  • Asychronous: Non-blocking request that allows other operations to continue while waiting for the response.
  • Promise-Based: Returns a promise, enabling better handling of success and error scenarios.
  • Flexible Request: Custumizable request allowing you to set headers, specify the HTTP method, and add parameters.
  • Cross-Origin Resource Sharing: Request facilitates communication with servers on different domains.

Making a FETCH Request

A Step-By-Step Breakdown

1. Create a FETCH Request:

  • To initiate a Fetch request, you use the fetch() function. The simplest form of a Fetch request takes the URL of the resource you want to retrieve as an argument:
fetch('https://api.example.com/data')
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });
Enter fullscreen mode Exit fullscreen mode

2. Handling the Response

  • The fetch() function returns a Promise that resolves to a Response object representing the server's response. To handle the response, you chain a .then() method to the fetch request. Inside the .then() method, you can access and process the response data:
fetch('https://api.example.com/data')
  .then(response => {
    // Handle the response
    // Access response data
    console.log(response);
  })
  .catch(error => {
    // Handle errors
  });
Enter fullscreen mode Exit fullscreen mode

3. Parse the Response:

  • By default, the response object doesn't provide the actual data. To extract the data, you need to use one of the response methods. For example, you can use the .json() method to parse the response body as JSON:
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // Process the JSON data
    console.log(data);
  })
  .catch(error => {
    // Handle errors
  });
Enter fullscreen mode Exit fullscreen mode

4. Error Handling:

  • To handle errors that may occur during the fetch request or response handling, you can chain a .catch() method at the end of the fetch request. This method allows you to catch and handle any rejected Promises:
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // Process the JSON data
    console.log(data);
  })
  .catch(error => {
    // Handle errors
    console.error('Error:', error);
  });
Enter fullscreen mode Exit fullscreen mode

HTTP Methods

  • GET: Used to retrieve data from a server.
  • POST: Used to submit data to the server.
  • PUT: Used to update or replace an existing resource on the server.
  • DELETE: Used to delete a resource(s) from the server.
  • PATCH: Used to partially update an existing resource.
  • HEAD: Used to retrieve only headers from a resource.

Conclusion

FETCH request are a great, modern API given to us by JavaScript to allow us to make network requests to servers to either retrieve or send data and resources. It's an excellent way to communicate with servers and handle responses, and by understanding the basics, you can build a fast and responsive web expierence. Use FETCH to take your development skills to the next level!

Top comments (1)

Collapse
 
prsaya profile image
Prasad Saya

You can also use fetch with async-await syntax.