Fetch API in JavaScript
Learn how JavaScript uses the Fetch API to request data from servers and work with asynchronous operations.
What is Fetch API?
The Fetch API is a modern JavaScript API used to make HTTP requests and communicate with web servers.
It can be used to retrieve data from an API, send data to a server, and work with JSON responses.
Simple Definition
Fetch API allows JavaScript to communicate with a server and get or send data over HTTP.
JavaScript sends a request, the server returns a response, and JavaScript processes the received data.
Fetch API Syntax
The basic Fetch API syntax starts with the fetch() function.
fetch("https://example.com/data")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
Example 1: Basic Fetch Concept
In a real application, fetch() can request data from an API. The example below shows the basic request flow.
fetch("https://example.com/api/data")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log("Error:", error);
});
Data received from the API.
Example 2: Fetch JSON Data
Most APIs return data in JSON format. The response.json() method converts the response into a JavaScript object.
fetch("https://example.com/api/student")
.then(function(response) {
return response.json();
})
.then(function(student) {
console.log("Name:", student.name);
console.log("Course:", student.course);
});
Course: JavaScript
Example 3: Fetch with async and await
Fetch API is commonly used with async and await to make asynchronous code easier to read.
async function getData() {
const response =
await fetch("https://example.com/api/data");
const data =
await response.json();
console.log(data);
}
getData();
Data loaded using async and await.
The CIIT JavaScript compiler is console-based. The Try It buttons use compiler-safe examples so that output appears immediately in the compiler.
The code displayed in the lesson shows the real Fetch API syntax, while the Try It version demonstrates the same concept without depending on an external API or network connection.
Why Use Fetch API?
Important Benefits
• Used to communicate with web servers.
• Can retrieve data from APIs.
• Can send data to servers.
• Works with JSON responses.
• Works well with Promises.
• Can be combined with async and await.
Summary
The Fetch API is used to make HTTP requests from JavaScript. It returns a Promise and can be used with then(), catch(), and async/await. Fetch API is commonly used when working with web APIs and server-side data.