Send HTTP GET Request Using the Fetch API
Updated: 17-Apr-2024 / Tags: Javascript Lang Reference / Views: 247 - Author: George
Introduction
With JavaScript's Fetch API, we can send asynchronous HTTP requests to retrieve data from either a local file or a database, using the Fetch API in conjunction with a server-side language like PHP.
By using the Fetch API to retrieve data stored in a JSON file, or from the database, we can eliminate the need for page refreshes, thereby saving time and providing an enhanced user experience.
In this tutorial I will try to explain as simply as possible how to send a GET request using the fetch method. I am going to show you a few examples. First on how to fetch the data from a JSON file, and second how to fetch data from a PHP file.
So let's start by building a GET request step by step to retrieve the data from a JSON file, while also learning the basics of the fetch() method.
Quick Answer
-
Send a GET request to a JSON file
To send a GET request to a JSON file to retrieve its data using the fetch() method, copy the code snippet below.
fetch("your-file.json") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("There was a problem with the fetch operation:", error));
-
Send a GET request to a PHP file
To send a GET request and fetch the data from a PHP file, change the argument to your PHP file. The rest of the code is the same as above.
fetch("your-file.php")
But be sure that the PHP file is returning JSON data.
$foods = ['Pizza', 'Burgers', 'Pasta', 'Fish']; echo json_encode($foods);
-
Send a query string with a GET Request
To send a query string to your PHP file, you must construct a key=value pair and append it to the end of the filename after a question mark.
fetch("your-file.php?name=Dennis")
And in the PHP file you can check for a GET request that matches the key=value pair query string.
if($_GET['name'] == "Dennis"){ $user = array("name" => "Dennis", "age" => "22", "gender" => "Male"); echo json_encode($user); }
If the quick answer section is covering you that is great. But if you feel like you want a more detailed explanation then keep reading.
The products.json file
Here we have the products.json file which we are going to use in our first example to retrieve its data.
[
{
"id": 1,
"image": "product-images/bike-1.jpeg",
"product-name": "Orient Vita Pro 28\"",
"price": "284.00",
"inventory": 4,
"productCode": "K203"
},
{
"id": 2,
"image": "product-images/bike-2.jpeg",
"product-name": "Orient S-400 26\"",
"price": "198.00",
"inventory": 14,
"productCode": "K433"
},
{
"id": 3,
"image": "product-images/bike-3.jpeg",
"product-name": "Bullet Bora 20\"",
"price": "350.00",
"inventory": 7,
"productCode": "K012"
},
{
"id": 4,
"image": "product-images/guitar-1.png",
"product-name": "Feder handmade",
"price": "790.00",
"inventory": 5,
"productCode": "G0127"
},
{
"id": 5,
"image": "product-images/guitar-2.png",
"product-name": "Ibanez G120",
"price": "430.00",
"inventory": 2,
"productCode": "G1233"
},
{
"id": 6,
"image": "product-images/guitar-3.png",
"product-name": "Feder Blues edition",
"price": "650.00",
"inventory": 6,
"productCode": "G4478"
}
]
The fetch method
Let's get familiar with the Fetch API and the fetch() method.
The Fetch API includes a method called fetch(), which belongs to the window object. Every method that belongs to the window object is accessible in the global scope, thus we can call it directly in our JavaScript file.
fetch()
When we send a GET request we have to pass in as an argument the path to the resource we want to fetch. In our case we have a file named products.json and we want to retrieve the data from it. So I will pass in the fetch method as an argument the path to the JSON file.
fetch("products.json");
If we execute this line of code we will send a successful GET request to the products.json file. But this is not enough we have also to retrieve the data.
The fetch() method returns a promise that resolves to a Response object. This Response object includes a method called then(). We chain the then() method to the fetch() method, allowing us to access the data from the JSON file
fetch("products.json")
.then()
The then() method takes as an argument a function, which function has also an argument in our case named response ( you can give any name you like to the argument, but naming it response makes more sense ).
fetch("products.json")
.then(function(response){
})
Inside the callback function we have to check if the response was successful. The Response object provides us with the response.ok property that we can use. If the response.ok property returns false we log to the console an error.
fetch("products.json")
.then(function(response){
if(!response.ok){
console.log("There was a network error");
}
})
Now we have to parse the data from the JSON file.
The Response object has methods to parse the fetched data in the format that we are
expecting.
- Response.json: This method is used to extract the JSON body content from the response. When you make a request to a server and receive a response containing JSON data, you can use Response.json() to parse that JSON data into a JavaScript object.
- Response.text: This method extracts the body content of the response as plain text. If the response contains text content, such as HTML, plain text, or XML, you can use Response.text() to retrieve it as a string.
- Response.blob: This method is used to extract the body content of the response as a Blob object, representing raw data. Blobs are useful for handling binary data, such as images or files.
In our case we expecting JSON data so we will use the Response.json() method.
fetch("products.json")
.then(function(response){
if(!response.ok){
console.log("There was a network error");
}
return response.json(); // Parsing the data as JSON.
})
But we cannot use the data yet. The response.json() method returns also a promise, so we have to chain another then() method to retrieve the data.
fetch("products.json")
.then(function(response){
if(!response.ok){
console.log("There was a network error");
}
return response.json(); // Parsing the data as JSON.
})
.then(function(data){
console.log(data); // Now we have the data from the file.
})
But we are not done yet. There is a last thing that we have to do and that is checking for any error in the promise chain using the catch() method.
The catch() method belongs to the Promise object. It is used specifically with promises to handle errors that may occur during asynchronous operations. The catch() method has to be the last method in the promise chain.
fetch("products.json")
.then(function(response){
if(!response.ok){
console.log("There was a network error");
}
return response.json(); // Parsing the data as JSON.
})
.then(function(data){
console.log(data); // Now we have the data from the file.
})
.catch(function(error){
// Log to the console any network error.
console.error("There was a problem with the fetch operation:", error);
});
Running the above code we will see in the console the fetched data from the products.json file.
Now we are done. We have build step by step a GET request using the fetch() method, and retrieved data from a JSON file.
Sending a simple GET request to PHP file
Now let's see how to send a GET request and fetch the data from a PHP file named script.php.
The PHP file
Let's see first the data that the PHP file returns.
The PHP file will return an array of foods. We use the json_encode() function to convert the $foods array to a JSON string.
<?php
$foods = ['Pizza', 'Burgers', 'Pasta', 'Fish'];
echo json_encode($foods);
The Javascript code
In the JavaScript code we will use the exact same GET request from the first example, but we will change the fetch() method's argument to script.php so we can target the PHP file.
fetch("script.php")
.then(function(response){
if(!response.ok){
console.log("There was a network error");
}
return response.json(); // Parsing the data as JSON.
})
.then(function(data){
console.log(data); // Now we have the data from the file.
})
.catch(function(error){
console.log(error); // Log to the console any network error.
});
Running the above code we will see in the console the foods array from the script.php file.
Sending a query string with the GET request to the PHP file
Let's see how to send a query string with the GET request to retrieve specific data from the PHP file.
The PHP file
Let's see the data that the script.php file returns.
In the script.php file, we will check if there is a GET request that contains a key named 'name'.
If this condition is true, we will further check if the value of the 'name' key is equal to 'Dennis'.
If this condition is also true, the PHP file will return an array named $user, which will be encoded into a JSON string.
if(isset($_GET['name'])){
if($_GET['name'] == "Dennis"){
$user = array("name" => "Dennis", "age" => "22", "gender" => "Male");
echo json_encode($user);
}
}
The JavaScript code
To send a query string along with the fetch() method we have to construct a key=value pair and append it at the end of the file after a question mark, like this: script.php?name=Dennis. Everything that comes after the question mark is called a query string.
fetch("script.php?name=Dennis")
.then(function(response){
if(!response.ok){
console.log("There was a network error");
}
return response.json(); // Parsing the data as JSON.
})
.then(function(data){
console.log(data); // Now we have the data from the file.
})
.catch(function(error){
console.log(error); // Log to the console any network error.
});
Running the above JavaScript code we will see in the console the $user array from the script.php file.
Summary
In this tutorial, we constructed a fetch process step by step and explained each step in detail. We learned how to send a GET request using the Fetch API to retrieve data from both a JSON file and a PHP file.
I Hope you find the article helpful. If you have any questions you can leave a comment.
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉