JavaScript - Fetch API
JavaScript - Fetch API
What is a Fetch API?
The JavaScriptFetch APIis a web API that allows a web browser to make HTTP request to the web server. In JavaScript, the fetch API is introduced in the ES6 version. It is an alternative of the XMLHttpRequest (XHR) object, used to make a βGETβ, βPOSTβ, βPUTβ, or βDELETEβ request to the server.
The window object of the browser contains theFetch APIby default.
The Fetch API provides fetch() method that can be used to access resources asynchronously across the web.
The fetch() method allows you to make a request to the server, and it returns the promise. After that, you need to resolve the promise to get the response received from the server.
Syntax
You can follow the syntax below to use the fetch() API in JavaScript
window.fetch(URL, [options]);
OR
fetch(URL, [options]);Parameters
The fetch() method takes two parameters.
- URLβ It is an API endpoint where you need to make a request.
- [options]β It is an optional parameter. It is an object containing the method, headers, etc., as a key.
Return value
It returns the promise, which you can solve using the βthenβ¦catchβ block or asynchronously.
Handling Fetch() API Response with βthenβ¦catchβ Block
The JavaScript fetch() API returns the promise, and you can handle it using the βthenβ¦catchβ block.
Follow the syntax below to use the fetch() API with the βthenβ¦catchβ block.
fetch(URL)
.then(data => {
// Handle data
})
.catch(err=> {
// Handle error
})In the above syntax, you can handle the βdataβ in the βthenβ block and the error in the βcatchβ block.
Example
In the below code, we fetch the data from the given URL using the fetch() API. It returns the promise we handle using the βthenβ block.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
Output
The data from the API is:
{"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}Handling Fetch() API Response Asynchronously
You can also solve the promise returned by the fetch() API asynchronously using the async/await keyword.
Syntax
Users can follow the syntax below to use the async/await keywords with the fetch() API.
let data = await fetch(URL);
data = await data.json();In the above syntax, we used the βawaitβ keyword to stop the code execution until the promise gets fulfilled. After that, we again used the βawaitβ keyword with the data.json() to stop the execution of the function until it converts the data into the JSON format.
Example
In the code below, we have defined the getData()asynchronous function to fetch the to-do list data from the given URL using the fetch() API. After that, we convert the data into JSON and print the output on the web page.
Output
The data from the API is:
{"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}Options with Fetch() API
You can also pass the object as a second parameter containing the options as a key-value pair.
Syntax
Follow the syntax below to pass the options to the Fetch() API.
fetch(URL, {
method: "GET",
body: JSON.stringify(data),
mode: "no-cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
redirect: "follow",
})Options
Here, we have given some options to pass to the fetch() API.
- methodβ It takes the βGETβ, βPOSTβ, βPUTβ, and βDELETEβ methods as a value based on what kind of request you want to make.
- bodyβ It is used to pass the data into the string format.
- modeβ It takes the βcorsβ, βno-corsβ, βsame-originβ, etc. values for security reasons.
- cacheβ It takes the β*defaultβ, βno-cacheβ, βreloadβ, etc. values.
- credentialsβ It takes βsame-originβ, βomitβ, etc. values.
- headersβ You can pass the headers with this attribute to the request.
- redirectβ If you want users to redirect to the other web page after fulfilling the request, you can use the redirect attribute.
Example: Making a GET Request
In the below code, we have passed the βGETβ method as an option to the fetch() API.
Fetch () API fetches the data from the given API endpoint.
Output
The status of the response is - success
The message returned from the API is - Successfully! Record has been fetched.
The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}Example (Making a POST Request)
In the below code, we have created the employee object containing the emp_name and emp_age properties.
Also, we have created the options object containing the method, headers, and body properties. We use the βPOSTβ as a value of the method and use the employee object after converting it into the string as a body value.
We make a POST request to the API endpoint using the fetch() API to insert the data. After making the post request, you can see the response on the web page.
Output
The status of the request is : success
The message returned from the API is : Successfully! Record has been added.
The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}Example (Making a PUT Request)
In the below code, we have created the βanimalβ object.
Also, we have created the options object. In the options object, we added the βPUTβ method, headers, and animal objects as a body.
After that, we use the fetch() API to update the data at the given URL. You can see the output response that updates the data successfully.
Output
The status of the request is : success
The message returned from the API is : Successfully! Record has been updated.
The data added is : {"name":"Lion","color":"Yellow","age":10}Example (Making a DELETE Request)
In the below code, we make a βDELETEβ request to the given URL to delete the particular data using the fetch() API. It returns the response with a success message.
Output
The status of the request is : success
The message returned from the API is : Successfully! Record has been deleted
The data added is - "2"Advantages of Using the Fetch() API
Here are some benefits of using the fetch() API to interact with third-party software or web servers.
- Easy Syntaxβ It provides a straightforward syntax to make an API request to the servers.
- Promise-basedβ It returns the promise, which you can solve asynchronously using the βthenβ¦catchβ block or βasync/awaitβ keywords.
- JSON handlingβ It has built-in functionality to convert the string response data into JSON data.
- Optionsβ You can pass multiple options to the request using the fetch() API.