A cheat sheet for JavaScript's fetch API
Tags: javascript, node, codenewbie, programming
Published: 2021-06-27 19:56:57

*Originally Posted on [realpythonproject.com](https://www.realpythonproject.com/a-cheat-sheet-for-javascripts-fetch-api/)*

<p><em>Connect with me on </em><a href="https://www.linkedin.com/in/rahulbanerjee2699/" rel="noreferrer noopener" target="_blank"><em>LinkedIn</em></a><em>, </em><a href="https://twitter.com/rahulbanerjee99" rel="noreferrer noopener" target="_blank"><em>Twitter</em></a></p>

The fetch API in JavaScript is used to make requests. It can also be used to consume APIs. Let's take a look at some of the most common operations using fetch API. 

I will be working in a NodeJs environment 

### Installing node-fetch
```bash
npm install node-fetch
```

### Importing node-fetch

```javascript
const fetch = require('node-fetch')
```

### A simple GET Request
#### With Promises 

Let's make a request to the [JSON Placeholder](https://jsonplaceholder.typicode.com/) 

```javascript
const fetch = require("node-fetch");
const url = "https://jsonplaceholder.typicode.com/todos/1";

fetch(url)
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((err) => console.log(err));
```
### With async/await
Under the hood, we are still using promises. Async/await makes the code look much more cleaner.
```javascript
const fetch = require("node-fetch");

const getData = async (url) => {
  const res = await fetch(url);
  const json = await res.json();
  console.log(json);
};

const url = "https://jsonplaceholder.typicode.com/todos/1";
getData(url);
```

### Passing Parameters

#### Add it to the URL
```javascript
const getData = async (url) => {
  const res = await fetch(url);
  const json = await res.json();
  console.log(json);
};
const url = "https://jsonplaceholder.typicode.com/posts?userId=1";
getData(url);
```
#### Using URLSearchParams
```javascript
const getData = async (url) => {
  const res = await fetch(url);
  const json = await res.json();
  console.log(json);
};
const params = {
  userId: 1,
};
const url =
  "https://jsonplaceholder.typicode.com/posts?" + new URLSearchParams(params);
getData(url);
```
> Note there is a ? at the end of the url

When you have multiple parameters, it looks cleaner to create an object with your parameters and use URLSearchParams to add it as a parameter in the request

### Passing a headers object
This is useful when the API you are consuming requires authentication. We will be working with the [Cats as a Service API](https://thecatapi.com/)

#### Loading env variables stored in .env files
We will need to install 'dotenv' using npm 
```bash
npm install dotenv
```
The below code snippet reads the environment variable 
```javascript
require("dotenv").config();
const CAT_API_KEY = process.env.API_KEY;
```
Let's try making a request to the API

```javascript
const getData = async (url,headers) => {
  const res = await fetch(url,{
      headers: headers
  });
  const json = await res.json();
  console.log(json);
};
const url =
  "https://api.thecatapi.com/v1/breeds";
const headers = {
    "x-api-key": CAT_API_KEY,
  };
getData(url,headers);
```
We simply create an object when making the request and store the headers object inside it.

### Handling Errors
Let's try to make a request to the Cat's API but to a non-existing endpoint.

```javascript
const getData = async (url,headers) => {
try{
    const res = await fetch(url,{
        headers: headers
    });
    if (res.status !== 200){
        throw ('Failed to get data from API')
    }
    
}
catch (err){
    console.log(err)
}
};
```
We can put the fetch request inside a try...catch block and throw our custom error message.

### Making a Post Request

```javascript
const getData = async (url,data) => {
  const res = await fetch(url, {
    method: 'POST',
    body: data,
  });
  const json = await res.json();
  console.log(json);
};
const url = "https://jsonplaceholder.typicode.com/posts";
const data = JSON.stringify({
  title: "test Data",
  body: "this is a test post request",
  userId: 120,
});
getData(url, data);
```
The we use JSON.stringify() to convert our data(object) into a string.

### Response Object
```javascript
const getData = async (url) => {
  const res = await fetch(url);
  const text = await res.text()
  console.log(text); // A string with the JSON
  console.log(res.status) // 200
  console.log(res.ok) // true
  console.log(res.url) // https://jsonplaceholder.typicode.com/posts/1
  console.log(res.redirected) // false
};
const url = "https://jsonplaceholder.typicode.com/posts/1";
getData(url);
```