Skip to main content

GET Request

Overview

Discover how to perform a GET request in JavaScript using the Fetch API. A GET request is commonly used for retrieving data from a server, and the Fetch API offers a modern approach to make asynchronous HTTP requests, simplifying the process of interacting with web services.

Code

function fetchDataFromApi(apiUrl) {
fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // Parse the response as JSON
})
.then((data) => {
// Handle the JSON data here
console.log("Data received:", data);
})
.catch((error) => {
// Handle any errors that occurred during the fetch
console.error("Fetch error:", error);
});
}

Example Usage

fetchDataFromApi("https://api.example.com/data");

Code Description

The fetchDataFromApi function is a versatile JavaScript function for making HTTP GET requests using the Fetch API. Here's an overview of its structure and behavior:

Function Parameter:

  • apiUrl: This is a string parameter that represents the URL from which data is to be fetched.

Fetch API Usage:

  • The function uses the Fetch API to perform a GET request to the provided apiUrl.
  • No additional configuration for headers or method is required, as GET is the default method for fetch.

Response Handling:

  • The first .then() block examines the response to check if it was successful (response.ok). If not, an error is thrown with the HTTP status.
  • If successful, the response is parsed as JSON.

Data Processing:

  • The second .then() block handles the processed data, which could include various operations like logging the data to the console or updating the UI.

Error Handling:

  • The .catch() block is used to catch any errors that occur during the fetch operation, such as network issues or problems with the request.

This function is designed to be easily reusable across different parts of a web application where data needs to be retrieved from a server, such as in data fetching for a dashboard, user profiles, or other information displays.

References