DEV Community

Cover image for Complete guide to Fetch API
Rahul
Rahul

Posted on • Updated on

Complete guide to Fetch API

This is not the same average blog post you have seen on many sites. This is something new and amazing.

The fetch API is a promise-based JavaScript API for making asynchronous HTTP requests in the browser.

It is a simple and clean API that uses promises to provide a powerful and flexible feature set to fetch resources from the server.

How to use fetch API ?

Using fetch API is really simple. Just pass the URL, the path to the resource you want to fetch, to **fetch() **method.

fetch( 'URL' )
      .then( red => {
                 // handle response data
  })
  .catch( err => {
                 // handle errors
  });
Enter fullscreen mode Exit fullscreen mode

Read More => filter() method explained

Making get requests

By default, the fetch API uset GET method for asynchronous requests. Lets see a very simple example. Here we will make a request to the "Dummy API", using fetch().

const url = "http://dummy.restapiexample.com/api/v1/employees"; 
fetchurl()
     .then(res => {
            console.log(res);
})
      .catch(err => {
             console.log('Error: ${err}' ); 
});
Enter fullscreen mode Exit fullscreen mode

Dummy API is a fake API service for testing and prototyping

Making post request

Fetch can also be used for any other HTTP method in the request: POST, PUT, DELETE, HEAD and OPTIONS. All you need to do is set the method and body parameters in the fetch() options.

const url = 'http://dummy.restapiexample.com/api/v1/create'
const user = {
      name: 'Rahul'
      age: '16'
      salary: '000'
};

const options = {
   method: 'POST'
   body: JSON.stringify(user), 
}

fetch(url, options)
     .then( res => res.json())
     .then( res=> console.log(res));
Enter fullscreen mode Exit fullscreen mode

Read more => map() method explained

Error handling

The catch() method can intercept any error that is thrown during the execution of the request. However, the promise returned by the fetch() doesn't reject HTTP errors like 404 or 500. For that, we can use the "ok" property of response object.

const url = "http://dummy.restapiexample.com/api/v1/employee/40";
fetch(url) //404 error
     .then( res => {
          if (res.ok) {
                return res.json( );
          } else {
                return Promise.reject(res.status); 
           }
      })
      .then(res => console.log(res))
      .catch(err => console.log('Error with message: ${err}') ); 
Enter fullscreen mode Exit fullscreen mode

Fetch and Async/Await

Since fetch is a promis-based API, we can go one step further and use the ES2017 async/await syntax to make our code even simpler.

const url = 'http://dummy.restapiexample.com/api/v1/employees'; 
const fetchUsers = async () => {
    try {
       const res = await fetch(url);
     // check for 404 error
       if (!res.ok) { 
           throw new Error(res.status);
       }
       const data = await res.json();
          console.log(data);
       }
       // catch block for network errors
       catch (error) { 
            console.log(error); 
        }
}
fetchUsers( );
Enter fullscreen mode Exit fullscreen mode

Help Needed Plz

Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.


1.png




⚡Happy Coding | Thanks For Reading😀.

Top comments (5)

Collapse
 
madsstoumann profile image
Mads Stoumann

It can also be a one-liner in an async block/method:

const data = await (await fetch(url)).json();
// do something with data
Enter fullscreen mode Exit fullscreen mode

Also worth mentioning is the AbortController, so you can cancel a fetch() after a set timeout:

if ('AbortController' in window) {
  const controller = new AbortController();
  const signal = controller.signal;
// etc.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rahxuls profile image
Rahul

Yea. Thanks.

Collapse
 
pradeepradyumna profile image
Pradeep Pradyumna

Good one Rahul! It was helpful!

Collapse
 
rahxuls profile image
Rahul

Thank you.

Collapse
 
rahxuls profile image
Rahul

Thanks You SO MUCH