DEV Community

Johnathon roy
Johnathon roy

Posted on

Learn to use fetch() in API call Easily

Today we are going to explore the fetch function in API calls and get to know about different methods (such as GET, POST, PUT and DELETE), Call Authentication and Interceptor.

XMLHttpRequest (XHR) was used before fetch() was introduced to make Http requests. An XMLHttpRequest would need two listeners to be set to handle the success and error cases and a call to open() and send(). It was more complex to understand and implement.

What is fetch() method?

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy and logical way to fetch resources asynchronously across the network.

fetch() allows us to make network requests similar to XMLHttpRequest. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

The fetch method only has one mandatory argument, which is the URL of the resource we wish to fetch

What are the different methods used by fetch()?
Some most popular methods used by fetch to make an HTTP request to an API are :

GET
POST
PUT
DELETE
GET

GET requests are the most common and widely used methods in APIs and websites. The GET method is used to retrieve data from the server at the specified resource. For example, say we have an API with a ‘/users’ endpoint. Making a GET request to that endpoint should return a list of all available users.

Since a GET request is only requesting data and not modifying any resource, it is considered as a safe and idempotent method.

GET is often the default method in HTTP clients

For a complete guide about this, you can use this ref link as well

Top comments (0)