In modern web development, we often fetch resources from external applications across the web using APIs.
APIs enable different web applications to interact with each other by providing standardized ways to access and retrieve data from diverse sources.
One of the common ways to perform API requests in JavaScript is using the Fetch API. We will explore the Fetch API, what it is, how it works, and how to use it.
Prerequisites
- An understanding of APIs and JavaScript Promises will help with comprehension. However, I will also explain in great detail.
How Fetch API works
The Fetch API provides a modern JavaScript interface for fetching resources. It was created to be a more powerful and flexible replacement for XMLHttpRequest. The Fetch API provides a flexible way to handle HTTP requests, with easier ways to interact with APIs and retrieve data from servers.
Basic Syntax of Fetch API
The fetch()
method initiates data retrieval using the Fetch API. It takes one mandatory argument: the URL of the resource to retrieve. Optionally, you can pass an options object that allows you to specify a number of settings like HTTP methods, headers, body, and more as the second argument.
Here is an example of a basic fetch request:
fetch("http://urlexample.com/info")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("error :" error))
The fetch()
method returns a Promise that resolves to the response of that request.
In the code above, we use the fetch()
method to fetch data from urlexample.com/info. The then()
method handles the response and converts it to JSON using the json()
method. The second then()
method logs the retrieved data to the console, and the catch()
method handles the error if the request fails.
The Fetch API and Promises
The Fetch API returns a Promise object, hence why we handle it using the then()
and catch()
methods, as shown in the examples above. The fetch()
method returns a Promise object that resolves to the response of that request. If you run a fetch method and assign the result to a variable, the variable will return a Promise object:
const response = fetch("http://urlexample.com/info");
console.log(response) //Promise {<pending>}
This code will log the Promise object assigned to the response variable in a pending state. If you wait a while and log the variable again, the output will be fulfilled:
const response = fetch("http://urlexample.com/info");
console.log(response) //Promise {<fulfillment>: Response}
On fulfillment, the fetch()
method will return a response object.
How to make a GET Request
The GET request is the most common type of HTTP method. We use it to retrieve data from a server. Here's how to make a GET request using the Fetch API:
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error()
In this code, the fetch()
method is makes a GET request to the URL (API endpoint) jsonplaceholder.typicode.com/users/1. On fetching data, we convert it to JSON and log data to console. In case it fails, we log the error to console.
Options Object
Previously, I mentioned that the fetch()
method can accept a second optional argument, an options object. It is an object containing custom settings you want to send with the request. Some of the possible options are:
body: you can specify any data you would like to add to your request: this can be a Blob, an ArrayBuffer, a TypedArray, a DataView, a FormData, a URLSearchParams, string object or literal, or a ReadableStream object. Note that a request using the GET or HEAD method cannot have a body.
cache: this is a string indicating how the request will interact with the browser's HTTP cache. The possible values are; default, no-store, reload, no-cache, force-cache, and only-if-cached.
credentials: controls how the browser handles credentials (cookies, HTTP authentication entries, and TLS client certificates). It uses one of the following strings: omit, same-origin, and include.
headers: headers you want to add to your request contained within the Headers object.
method: the default method is GET. However, you can specify other methods like POST, PUT, PATCH, and DELETE.
How to make a POST Request
A POST request sends data to a server. We use it when submitting forms or sending data to create a new resource. Let's look at how to make a POST request using the Fetch API:
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: "John Doe",
email: "johndoe@yahoo.com"
}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("error :", error))
In this code, the fetch()
method is used to make a POST request to the URL (API endpoint) jsonplaceholder.typicode.com/users. When sending a POST method, you need to modify the options object to get your desired result. In this case, we did the following:
defined a method property and set it to the right request method (POST)
we used the headers property to indicate the type of data sent in the request
the body property contains data being sent along the request.
In the body property, we converted a regular JavaScript object to JSON using the JSON.stringify()
method.
The response from typicode.com API will look similar to this:
This means that we successfully created a new user. However since we are using a fake API, we can't really add a user.
How to use Async/Await with the Fetch API
Since the Fetch API returns a Promise object, we can use the async/await
syntax to replace the .then()
and .catch()
methods.
Let's look at a GET request using fetch()
in async/await syntax:
async function getData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users")
const result = await response.json();
console.log("Success:", result);
} catch (error) {
console.error("Error:", error)
}
}
How to Handle Errors
Handling errors is a crucial part of making robust applications. The Fetch API provides an easy way to catch and handle errors that may occur during a request.
Let's look at an example of handling errors in a fetch request:
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => {
if(!response.ok) {
console.log(`status: ${response.status}`)
}
return response.json()
})
.then(data => console.log("Userdata :", data))
.catch(error => console.error("error :", error))
In this code, we added additional information to the request using the response object read-only property ok
to check if the response was successful or not.
Conclusion
Working with APIs is an essential aspect of modern web development. The Fetch API provides a simple way to interact with external resources.
This article has covered the basic syntax of Fetch API and how to handle responses from the Promise object. Furthermore, we explored the GET and POST request methods, discussed using async/await syntax, and finally, how to handle errors.
As you continue to practice and implement some of these concepts, you will gain more understanding of using Fetch API to interact with external data sources.
Thank you for reading. Please do well to like and share this article with someone who could learn from it.