Fetch API
Request data from APIs using the Fetch API.
Modern websites often need to communicate with external services to retrieve information such as weather updates, product details, user profiles, news articles, or payment information. This communication is usually done through APIs.
JavaScript provides the Fetch API, which allows websites to request data from servers and display it dynamically.
What Is an API?
API stands for Application Programming Interface.
An API acts as a bridge that allows two applications to communicate with each other, similar to a waiter carrying orders between a customer and a kitchen.
Why Are APIs Important?
- Weather applications
- Social media platforms
- Online shopping websites
- Banking applications
- Maps and navigation systems
What Is Fetch?
The Fetch API is a built-in JavaScript feature used to make HTTP requests to servers. Fetch returns a Promise, making it useful for asynchronous operations.
Fetching Data with GET Requests
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});How it works:
- fetch() sends a request to the server.
- The server returns a response.
- response.json() converts the response into JavaScript data.
- The data is displayed or processed.
- Errors are handled using catch().
Using Async/Await with Fetch
async function getUsers() {
try {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
getUsers();This approach makes asynchronous code look more like regular JavaScript.
Sending Data with POST Requests
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
age: 25
})
});What Is JSON?
Most APIs exchange data using JSON, or JavaScript Object Notation.
{
"name": "John",
"age": 25
}Real-World Example
In a weather application, JavaScript uses Fetch to send a request to a weather API, receives the current weather information, and displays it instantly.
Error Handling
fetch("https://api.example.com/data")
.catch(error => {
console.log("Request failed");
});Summary
APIs allow applications to communicate and exchange data, while Fetch provides a simple way for JavaScript to make requests to servers. Fetch, JSON, Promises, and Async/Await form the foundation of data-driven web applications.