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
Importing node-fetch
const fetch = require('node-fetch')
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));
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);
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);
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);
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
The below code snippet reads the environment variable
require("dotenv").config();
const CAT_API_KEY = process.env.API_KEY;
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);
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)
}
};
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);
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);
3 comments
Comments are closed.