Fetch API

fetch api.png

Hello there,

In this entry, I would like to share one way to get JSON data from a Rest API that I find useful.

The Fetch API provides an interface to access and manipulate requests and responses. Fetch is a good way to avoid a ‘callback mess’ since it uses Promises. The Fetch API possesses a method named fetch() which fetch a resource.

A basic syntax for a fetch() function looks like this:

fetch api.png

The fetch function requires an argument, which is the URL from where you want to fetch a response. It will always return a promise whether it is successful or not.

The .then() function will receive a Response object, in case the request is successful. If it fails, the .catch() function will receive an error instead.

Something important to keep in mind is that when the promise is resolved we are getting the response header but not the response body.

In order to get the actual data (response body), we do the following:

fetch-api-1.png

We call the .json() method on the Response object which returns a Promise.

Next, we can chain another .then() to receive the data when the .json() promise is resolved. The data will be passed as an argument to the callback function that you are passing to the .then() method. In this case, I’ve named this parameter ‘data’.

Fetch API is a great way to make asynchronous requests, handle responses using JavaScript promises in the process.

Previous
Previous

Generator Functions

Next
Next

Value vs Reference Types