Get and Post method using Fetch API
Last Updated :
24 Sep, 2024
The fetch() method is used to send HTTP requests to the server without refreshing the page, providing an efficient alternative to the older XMLHttpRequest object. One of the main advantages of fetch() is that it uses Promises, which allow for better management of asynchronous operations compared to callbacks. Promises help avoid "callback hell," where nested callbacks can become difficult to read and maintain.
However, it's worth noting that not all browsers support fetch() natively. For older browsers, you may still need to rely on the XMLHttpRequest object or use polyfills to ensure compatibility.
The fetch() method can handle different types of HTTP requests, such as GET, POST, PUT, and DELETE. In this article, we'll explore how to use the fetch() API with practical examples.
Basic Syntax of fetch()
The basic syntax for a fetch() request looks like this:
javascript
fetch(url, {options})
.then(data => {
// Do some stuff here
})
.catch(err => {
// Catch and display errors
})
Fetch vs. XMLHttpRequest
- Promises in fetch(): Unlike XMLHttpRequest, fetch() is based on Promises, which makes it easier to manage multiple asynchronous operations.
- Readable code: fetch() leads to more readable and maintainable code compared to callbacks in XMLHttpRequest.
- Browser compatibility: While fetch() is widely supported, some older browsers may not support it. In such cases, XMLHttpRequest may still be necessary.
Using fetch() with Different HTTP Methods
Example 1: GET Request using fetch()
A GET request is used to retrieve data from a server. Let’s use https://jsonplaceholder.typicode.com/, a free REST API that returns sample data such as posts and users.
HTML Code:
First, create a basic HTML file that includes a JavaScript script where we’ll make our fetch requests.
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fetch API</title>
</head>
<body>
<div>
<h1>Fetch API GET REQUEST</h1>
<h3>Fetching Users</h3>
<!-- Table to display fetched user data -->
<table id="users"></table>
</div>
<!-- Link JavaScript file -->
<script src="main.js"></script>
</body>
</html>
JavaScript Code (GET Request):
In the JavaScript file (e.g., script.js), write the following code to fetch user data from the API:
javascript
// main.js
// GET request using fetch()
fetch("https://jsonplaceholder.typicode.com/users")
// Converting received data to JSON
.then(response => response.json())
.then(json => {
// Create a variable to store HTML
let li = `<tr><th>Name</th><th>Email</th></tr>`;
// Loop through each data and add a table row
json.forEach(user => {
li += `<tr>
<td>${user.name} </td>
<td>${user.email}</td>
</tr>`;
});
// Display result
document.getElementById("users").innerHTML = li;
});
Now, when you open the HTML file you'll see the result as follows:

When you open DevTools in Chrome (Press F12) you'll see that a fetch request has been made to the route users.

You can get more data from the request, refer to the https://jsonplaceholder.typicode.com/guide/documentation.
Example 2: POST Request using fetch()
A POST request is used to send data to the server, commonly for submitting forms or adding new data. In this example, we'll send a POST request to add a new post to the posts endpoint of the JSONPlaceholder API. The server will return the created post with a unique ID.
JavaScript Code (POST Request):
Add the following code to your script.js file to perform a POST request:
javascript
// main.js
// POST request using fetch()
fetch("https://jsonplaceholder.typicode.com/posts", {
// Adding method type
method: "POST",
// Adding body or contents to send
body: JSON.stringify({
title: "foo",
body: "bar",
userId: 1
}),
// Adding headers to the request
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
// Converting to JSON
.then(response => response.json())
// Displaying results to console
.then(json => console.log(json));
Now if you open your javascript console and refresh the page you'll see a result like below:

The API returns a status of 201 which is a HTTP status code for Created.
Handling Errors with fetch()
It's important to note that fetch() will only reject a Promise if there’s a network failure. It does not automatically reject responses with a status code outside the 2xx range (such as 404 or 500 errors). Therefore, you must manually check the response status using response.ok.
JavaScript
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Handle successful response
})
.catch(error => {
console.error('Fetch error:', error);
});
Similar Reads
How to test an API using Postman ?
API testing is a software testing type that tends to validate the application programming interfaces. As per Postman API, API testing is confirming that an API is working as expected. It sends requests to an API and monitors the responses to check its behavior to assess the functionality, reliabilit
5 min read
Simple POST request using the fetch API
The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API Syntax: fetch(url, { config }) .then
2 min read
Difference between HTTP GET and POST Methods
HTTP (Hypertext Transfer Protocol) specifies a collection of request methods to specify what action is to be performed on a particular resource. The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. This article covers the 2 most common HTTP request methods, i.e. the GET
4 min read
How to use JavaScript Fetch API to Get Data ?
The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests. Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity, and a few more. H
2 min read
How to Make API Call Using Python
APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see ho
3 min read
How To Use JavaScript Fetch API To Get Data?
An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
4 min read
Flask HTTP methods, handle GET & POST requests
In this article, we are going to learn about how to handle GET and POST requests of the flask HTTP methods in Python. HTTP Protocol is necessary for data communication. In the context of the World Wide Web, an HTTP method is a request method that a client (e.g. a web browser) can use when making a r
6 min read
How to generate API documentation using Postman?
Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. In this article, you will learn how to generate API
2 min read
Create and Send API Requests in Postman
Postman serves as a flexible tool, simplifying the system of crafting and checking out API requests. In the world of software, APIs(Application Programming Interfaces) are the constructing blocks for packages to speak with each other. In this article, you will find out how Postman turns into your go
4 min read
API documentation in Postman: Purpose and Benefits
Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript,
4 min read