DEV Community

Cover image for Mastering The Fetch API In Javascript: A Comprehensive Guide.
Pauline Oraro
Pauline Oraro

Posted on

Mastering The Fetch API In Javascript: A Comprehensive Guide.

In the realm of web development, handling network requests and fetching data from servers is a common task. The fetch API in Javascript has become the go to solution for making HTTP requests that offers a more modern and user-friendly approach compared to XMLHttpRequest. In this guide, we will delve into the fetch API, exploring its capabilities, syntax and best practises to empower you to master this essential tool for web development.

Table of contents

Defination of terms

Meaning of A.P.I
A.P.I stands for application programming interface. It is a software intermediary that allows two applications to communicate with each other. They are an accessible way to extract and share data within and across applications.

XMLHttpRequest
It is an object in Javascript that allow you to make HTTP requests to a web server from a web page. It is commonly used to retrieve data from a server without requiring the entire web page to be refreshed.

HTTP Requests
The Hypertext Transfer Protocol is designed to enable web clients such as browsers to request resources like webpages, images or data from web servers. HTTP methods define the action to be performed on the resource. The methods are;

  • get- retrieve data from the server.

  • post- send data to the server to be processed.

  • put- update an existing resource on the server.

  • delete- remove a resource from the server.

What is Fetch API

The fetch API is a Javascript interface that provides a straightfoward and flexible way to make network requests. It allows you to fetch resources such as webpages, images or other files from servers using HTTP or HTTPS protocols. The fetch API uses promises making it more elegant and easier to work with asynchronous operations.

Fetch API syntax

fetch(url)  
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));
Enter fullscreen mode Exit fullscreen mode

The fetch (url) initiates a get request to the specified url. This part sends the request and returns a promise that resolves to the response from the server.

The first ".then()" in the promise chain takes the response returned from the fetch call and calls the ".json()" method on it. This method parses the response body as JSON.

The second ".then()" takes the parsed JSON data returned from the previous ".then()" and logs it into the console.

The catch block will catch the error and log it into the console.

Let's create a random user generator

This project example fetches and displays a random user data from the specified url when a button is clicked. You can view the live demo here random user generator.

var img = document.querySelector("img");
var fullname = document.querySelector("#fullname");
var username = document.querySelector("#username");
var email = document.querySelector("#email");
var city = document.querySelector("#city");
var gender = document.querySelector("#gender");
var btn = document.querySelector("button");
var url = 'https://randomuser.me/api';

btn.addEventListener("click", function(){
  fetch(url)
  .then(handleErrors)
  .then(parseJSON)
  .then(updateProfile)
  .catch(printErrors)
})

function handleErrors(res){
  if (!res.ok){
    throw Error("There are some errors:" + res.status)
  }
  return res;
}

function parseJSON(res){
  return res.json().then(function(parsedData){
    return parsedData.results[0];
  });
}

function updateProfile(data){
  img.src = data.picture.medium;
  fullname.innerText = "Name: " + data.name.first + " " + data.name.last;
  username.innerText = "Username: " + data.login.username;
  gender.innerText = "Gender: " + data.gender;
  email.innerText = "Email: " + data.email;
  city.innerText = "City: " + data.location.city;
}

function printErrors(error){
  console.log(error);
}
Enter fullscreen mode Exit fullscreen mode

HTML elements
Select various HTML elements using the document.querySelector and assigns them to variables.

event listener
Add an event listener to the "btn" element for the click event. When the button is clicked it triggers a sequence of actions using the fetch API to retrieve random user data from the specified url.

fetch url
It is chained with several ".then()" and "catch()" methods to handle the asynchronous flow of data.

handleErrors() function
It is called in the ".then()" block after the initial fetch. It checks if the response from the API is successful (HTTP status code 200) using "res.ok". If there is an error (the API returns an error status code) it throws an error with a message including the HTTP status code.

parseJSON () function
It is called after the response is successfully retrieved. It parses the response as JSON data using ".json()" method and returns the first result from the parsed data.

updateProfile() function
It takes the parsed data and updates various HTML elements on the page with user's information.

printErrors() function
If any error occurs at any point in the promise chain they are caught and handled by the function which logs the errors to the console.

In summary, when the button is clicked this code makes an API request to the specified url, handles any potential errors, parses the response as JSON data and updates the page with the retrieved user's information or logs an error if something goes wrong.
It is a simple example of making an API request and updating a web page with the fetched data.

Conclusion

In the world of modern web development, the Fetch API has become an indispensable tool for fetching data asynchronously. Its simplicity, versatility, and seamless integration with Promises make it a valuable asset in building responsive and dynamic web applications. By mastering the Fetch API, you open the doors to a world of possibilities in creating powerful and efficient web solutions.

Top comments (0)