What is Fetch API?
The Fetch API is used to get or send data between JavaScript and a server.
It is commonly used to work with APIs.
Simple Example
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
How Does It Work?
fetch()
↓
Request to server
↓
Response
↓
response.json()
↓
Data
Step 1: fetch()
fetch(url)
Sends a request to the server.
Step 2: response.json()
response.json()
Converts the response into JavaScript data.
Step 3: then()
.then(data => {
console.log(data);
})
Uses the received data.
Step 4: catch()
.catch(error => {
console.log(error);
})
Handles errors.
Fetch with POST
We can also send data to a server.
fetch("https://example.com/users", {
method: "POST",
body: JSON.stringify({
name: "Maha"
})
});
Important Point
fetch() returns a Promise.
So we can use:
.then()
.catch()
with Fetch API.
Simple Formula
Remember:
fetch()
↓
response
↓
response.json()
↓
data
Conclusion
Fetch API = Communicating with a server using JavaScript.
It is mainly used to get or send data through APIs.
Top comments (0)