FetchApi().innerHTML = "dive into it"

rounit08

Rounit Ranjan Sinha

Posted on March 13, 2023

FetchApi().innerHTML = "dive into it"

As a frontend developer this can never happen that you would be not playing with APIs. Building APIs and Showing the data from those APIs to the user, both comes from a very different backgrounds but both of them are equally important.

We can call APIs by different methods out there, but using and starting with one of the most popular methods is important and that is "fetch" method.

Image description

Let's understand this with a simple piece of code.

Image description

So, in this code we are using a free public Api.
As you can see we are using two params in the fetch method and first one is "URL of the API".

Now, as the second params we are passing an Object which has some props like method, headers and body.

1)method:
In the method prop we pass different type of HTTP request methods (specifically only that method which is suitable for that particular logic)

First understand about HTTP Methods,
HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.

GET
The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

POST
The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server.

PUT
The PUT method replaces all current representations of the target resource with the request payload.

DELETE
The DELETE method deletes the specified resource.

and more methods.

2)body:

In this we pass the key-value pairs which we wanna pass to the API.
but the data are in JSON form so, it will demand a method i.e., JSON.stringify().

3)headers:

As we are passing JSON data so we need to tell API that in which form we are passing data.
So we give "content-type" property and in this case it is "json"

Read more at:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Hope it helps :)

💖 💪 🙅 🚩
rounit08
Rounit Ranjan Sinha

Posted on March 13, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related