How to Fetch data from an API using the JavaScript Fetch method
Tags: beginners, javascript, webdev, tutorial
Published: 2022-09-14 22:42:30

In building web apps with JavaScript, we may have to send a network request to a server and load new information when needed. 
For instance, we can use a network request to 
- Submit an order
- Load information, receive updates from a server, etc.

There are numerous ways to send a request and receive information from a server. A recommended approach is to use the `Fetch` API, which permit developers to make `http` request to web servers for resources needed to build web applications. 

In this tutorial, you will learn about the JavaScript Fetch API. By the end of the tutorial, you should be able to use the `fetch()` method to fetch for information from a server. Let's get started !

## What is the JavaScript Fetch API ?
> The JavaScript Fetch API is a modern interface use to fetch for resources from a server. This is achieved by sending an HTTP request to the server from the web browser.

The Fetch API includes a `fetch()` method, which starts the process of fetching information from any web server, and working with the information fetched. 
Using the `fetch()` method, we can receive data from a server, and even post data to the server.

## What is the `fetch()` method ?

> In JavaScript, the `fetch()` method is used to make asynchronous requests to the server and load the information that is returned by the server onto the web pages.

The syntax for the `fetch()` method is 

```
fetch(URL, options)
``` 
 The `fetch()` method accepts two arguments: 

 - `URL`: The URL to access
- `options`: An object which consists of additional properties (methods, headers) sent to the server.

Without options, we will only be downloading contents of the URL

###  Fetching for resources
To fetch for some resource, you will call the `fetch()` method, and pass it one argument : a`URL` (which indicates the path to the resource you want to fetch).

```
const promise = fetch(url)
``` 
The `fetch()` method returns a `Promise`, which can either be resolved or rejected. 

- The promise resolves into a `Response` object.  The `Response` object has a number of useful properties and methods to explore what we got from the request. 
- The promise `rejects` if the `fetch()` method was unable to make the HTTP-request. Rejections can be due to network problems, or if no such URL exits.

We chain the `fetch()` method with a `then()` and `catch()` method to enable us to use the response.

- The `then()` method is basically used to handle asynchronous tasks (tasks that are time-consuming), such as fetching data from an API. When we get a response from the `fetch()` method, we will handle the response in the `then()`. 
- Usually, we get a `Response` object from the fetch request. This object contains useful properties and methods.
- If there is an error in fetching the request, for instance due to network problems or invalid URL, the `catch()` method will handle this error.

The complete syntax for fetching information from a server is as below:

```
fetch(url)
    .then(response => {
        // handle the response object
    })
    .catch(error => {
        // handle the error
    });


``` 

### Reading the `Response` object
The `Response` object contains further data that needs to be converted into the required format in order to work with it. 
There are several methods you can use to read the body of the response object, one such method is the `json()` method. 
- The `json()` method returns another `Promise` that decides the complete data of the fetched resource. 
- We then access the data in another `.then()` method

### Example of  fetching and reading data from an API
In the code below, we will fetch a dummy phone product from the [dummyjson.com](https://dummyjson.com/) server, and then log the fetched data.

```
fetch('https://dummyjson.com/products/1')
	.then(response => response.json())
	.then(data => console.log(data))
	.catch(err => console.error(err));

``` 
#### Steps for fetching and reading data from an  API

- Pass the `fetch()` method the required `url` to get the data from. In this instance, the `URL` will be `https://dummyjson.com/products/1`
- Chain the `fetch()` method with the `then()` method
- If all goes well, in the `then()` method, we will receive a `Response` object from the server
- Extract the JSON body content from the `Response` object using the `json()` method.
- The `json()`  method will return a second`Promise`. This `Promise` will resolve to  contain the **fetched data**
 - Pass this data to another `then()` method.
- In the `then()`method, we can now  print the fetched data to the console or assign it to a variable.
- If there is an error in fetching the data, the `catch()` method will capture the error, and we can log that error

### Example 2: Fetching data from fake store API
In this instance, we will fetch a single ecommerce product from the [Fake Store API](fakestoreapi.com).
The fake Store API is a free online REST API we will be using to fetch pseudo-real data for our ecommerce website.

- Call the `fetch()` method and pass the `url` or API endpoint as the argument.
- The API endpoint or the `url` for this instance is : `'https://fakestoreapi.com/products/1'`. It provides access to a single product

```
fetch('https://fakestoreapi.com/products/1')
``` 

- Calling this`fetch()` method returns a special JavaScript object called `Promise`. The `Promise` produces a value (`Response` object ) after an asynchronous operation successfully completes, or an error if unsuccessful.
- Chain the `fetch()` method with a`then()` method to investigate the `Response` object we got from the API call.
- The `Response` object is assigned to a `response` variable. (You can give the `Response` object any variable name of choice, `res` or `response` is the convention)
- Use the `json()` method to view the complete content of the fetched resource ( For instance `res.json()` or `response.json()` depending on how you named your variable)


```
fetch('https://fakestoreapi.com/products/1').then(response => response.json())

``` 
- Finally, access the fetched data by chaining another `.then()` method


```
fetch('https://fakestoreapi.com/products/1')
  .then(
  // view the  complete content of the response
  response => response.json())
  .then(
  //access the actual data 
  data => console.log(data))
``` 
The output will be an object containing some dummy phone data- `title`, `price`, `description` etc.


```
{
  "id": 1,
  "title": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
  "price": 109.95,
  "description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
  "category": "men's clothing",
  "image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
  "rating": {
    "rate": 3.9,
    "count": 120
  }
}
``` 
- Instead of logging the output, you can assign this value to declared `variable`, and access the relevant data using the appropriate `key:value` pair.

## Handling the status code of the response

In the `Response` object, you can use the `status` and `statusText` properties to access the status code and status text, respectively. 

> An HTTP status code is a server response to a browser's request. When you visit a website, your browser sends a request to the site's server, and the server then responds to the browser's request with a three-digit code: the HTTP status code.

In the code below, we read the status code and status text from the server's response:

```
fetch('https://dummyjson.com/products/1')
	.then(response => {
  console.log(response.status) // check the status code of the response object
  console.log(response.statusText) // an interpretation of the code 
  return response.json() // read the actual data from body of the response object
})
	.then(data => console.log(data))
	.catch(err => console.error(err));
``` 

- A successful request will give a status code of `200` and a status text of `OK`
- If the requested URL throws a server error, the status code will be `500`.
- If the requested resource does not exist, the status code will be `400` and status text will be `Not found`


## Summary

- The `Fetch API` allows you to reqeust for a resource from a web server
- The `Fetch API` provides access to the `fetch()` method that returns a `promise` which resolves into a `Response` object
- Use the `json()` method to fetch the actual data
- Use the `status` and `statusText` properties of the`Response` object to investigate the status of the response
- Use the `catch()` method to handle a failed request, for instance network problemsn

That's all devs, go ahead and try fetching some data from your favorite APIs.

If you have found this article useful, please share on your social media handles, and follow my blog too. I would love to read your comment and feedback too.
Let's connect on [Twitter ](https://twitter.com/emmanuelfkumah)