DEV Community

Rounit Ranjan Sinha
Rounit Ranjan Sinha

Posted on

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 :)

Top comments (2)

Collapse
 
ravavyr profile image
Ravavyr

This is not a good deep dive.
The HTTP Methods do not actually "DO" anything at all. The server endpoint that receives the request has to be programmed to "post","get","put",and "delete".
The request TELLS the endpoint what it expects to receive in return, but you can easily make a "post" do all of the above behaviors. [I've always advocated we just have POST and manage everything that way since it doesn't matter, but hey, that's just my preference]

I suppose the deep dive begins when your readers click the link to mozilla.org since that also covers the response headers and error codes that can potentially come back from an endpoint.

There's honestly a lot more to cover in regards to "fetch" requests, but i find your article lacking. Instead of a "deep dive", perhaps retitle it to "an initial look at Fetch requests"

Collapse
 
rounit08 profile image
Rounit Ranjan Sinha

Thanks for your valuable additions :)