DEV Community

Cover image for A cheat sheet for JavaScript's fetch API
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

A cheat sheet for JavaScript's fetch API

Originally Posted on realpythonproject.com

Connect with me on LinkedIn, Twitter

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

npm install node-fetch
Enter fullscreen mode Exit fullscreen mode

Importing node-fetch

const fetch = require('node-fetch')
Enter fullscreen mode Exit fullscreen mode

A simple GET Request

With Promises

Let's make a request to the JSON Placeholder

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));
Enter fullscreen mode Exit fullscreen mode

With async/await

Under the hood, we are still using promises. Async/await makes the code look much more cleaner.

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);
Enter fullscreen mode Exit fullscreen mode

Passing Parameters

Add it to the URL

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);
Enter fullscreen mode Exit fullscreen mode

Using URLSearchParams

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);
Enter fullscreen mode Exit fullscreen mode

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

Loading env variables stored in .env files

We will need to install 'dotenv' using npm

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

The below code snippet reads the environment variable

require("dotenv").config();
const CAT_API_KEY = process.env.API_KEY;
Enter fullscreen mode Exit fullscreen mode

Let's try making a request to the API

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);
Enter fullscreen mode Exit fullscreen mode

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.

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)
}
};
Enter fullscreen mode Exit fullscreen mode

We can put the fetch request inside a try...catch block and throw our custom error message.

Making a Post Request

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);
Enter fullscreen mode Exit fullscreen mode

The we use JSON.stringify() to convert our data(object) into a string.

Response Object

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
rahulbanerjee99 profile image
Rahul Banerjee

Yes, you are correct. Thanks for pointing that out. With async/await and without async/await would make more sense.

 
alizulfaqar profile image
Ali Zulfaqar

Thank you for the comment

Collapse
 
alizulfaqar profile image
Ali Zulfaqar • Edited

Hello, just want to ask. Which is better to use to do POST and GET methods? For now I am using the normal fetch method.