JavaScript Fetch API

JavaScript Fetch API with examples

In this article, you’ll learn about the JavaScript Fetch API with examples and how to use it to make asynchronous HTTP queries.

JavaScript now has its own built-in method for making API requests. This is the Fetch API, a new standard for making server requests using Promises that also includes extra features.

In this tutorial, you will use the Fetch API to construct GET and POST queries.

Also Read: How to validate Forms in Javascript?

Basic Fetch API Syntax


The fetch() method takes only one parameter, which is the URL of the resource.

let response = fetch(url);

The fetch() method returns a Promise, which you can handle with the then() method:

fetch(url).then(response => console.log(response))

The function within the then() method is executed if the Promise returned is resolved. In this situation, the response is available in the then() method so you can handle it according to your logic.

If the Promise returned is reject then the catch() method is executed.

fetch(url).then(response => {

   console.log(response);

}).catch(error => {

   console.log(error);

});

Usage of Fetch API with real API

We will use the JSONPlaceholder API in the following code samples. You’ll collect some users through the API and use JavaScript to display them on the page.

The response parameter of the then() method takes the value of the object returned from fetch(url). You may use the json() method to convert response into JSON format:

Let’s look at the following example:

let url = 'https://jsonplaceholder.typicode.com/users';

fetch(url).then(response => response.json())

You can process this JSON data by adding another then() method with a parameter. for example, we will use an arrow function to manipulate the data.

let url = 'https://jsonplaceholder.typicode.com/users'; 

fetch(url)

    .then(response => response.json())

    .then(data => console.log(data))

Once you return, response.json() you will get the response in a nice JSON format in the data (parameter of then() ) method.

It may look like this:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },

...

]

The JSON format is easy to handle in JavaScript. You can use the map method or filter method in JavaScript to use the data according to your needs.

let url = 'https://jsonplaceholder.typicode.com/users';

fetch(url)

	.then(response => response.json())

	.then(data => {

		let users = data;

		users.map(user => {

			console.log(`Name: ${user.name}`);
			console.log(`Email: ${user.email}`);

		})
	});

The output will display the user name and emails in the console. You may test the above code in the browser console to see the result.

Name: Leanne Graham
Email: [email protected]
...

Fetch API – Handle the status codes of the Response

The status and statusText properties of the response object provides the status code and text. The status code for a successful request is 200, and the status text is OK:

let response = fetch("https://jsonplaceholder.typicode.com/users")

.then((response) => {

    console.log(`Status Text: ${response.status}`); // 200

    console.log(`Status Text: ${response.ok}`); // true
    
  });

Handling POST Requests

To make a POST request, we must include further parameters to fetch() method such as method, headers, and so on.

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));

Add comment