The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses
Using the Fetch API
With the Fetch API, you make a request by calling fetch(), which is available as a global function in both window and worker contexts. You pass it a Request object or a string containing the URL to fetch, along with an optional argument to configure the request.
The fetch() function returns a Promise which is fulfilled with a Response object representing the server's response. You can then check the request status and extract the body of the response in various formats, including text and JSON, by calling the appropriate method on the response.
Here's a minimal function that uses fetch() to retrieve some JSON data from a server:
Syntax:
fetch(url)
.then
(res=> res.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
GET - Get data from server
POST - Send data to server
PUT - Update full resource
DELETE - Delete a resource
GET Request to Retrieve Data
- fetch() sends the GET request to the specified URL.
- The response.json() method parses the JSON response.
- .then() logs the list of items once they are fetched
.fetch('https://fakestoreapi.com/products/1')
.then(response => response.json())
.then(items => console.log(items))
*POST Request to Submit Data
*
- The method: 'POST' tells Fetch to send data to the server.
- The headers include the Content-Type to indicate we are sending JSON.
- The body contains the data to be sent, which is stringified using JSON.stringify().
const data = { name: 'Pranjal', age: 25 };
fetch('https://fakestoreapi.com/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log(result));
*PUT Request to Update Data
*
const updatedData = { id: 1, price: 300 };
fetch('https://fakestoreapi.com/products/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedData)
})
.then(response => response.json())
.then(result => console.log(result));
- The method: 'PUT' indicates we are updating data.
- The body sends the updated data, converted to JSON.
- The response is parsed as JSON, and the updated result is logged.
DELETE Request to Remove Data
fetch('https://fakestoreapi.com/products/1', {
method: 'DELETE'
})
.then(response => response.json())
.then(result => console.log('Deleted:', result));
- method: 'DELETE' indicates that we want to delete the specified resource.
- The response is parsed as JSON to confirm the deletion.
- The result is logged to indicate the operation was successful.
Top comments (0)