DEV Community

Johnathon roy
Johnathon roy

Posted on

3

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

The Fastest, Most Accurate API for Voice AI

Ad Image

Building an AI Agent that needs to deliver human-like conversations? | Speechmatics’ real-time ASR is available in 50 languages and can understand speech in a fraction of a second.

Try Free

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay