Fetch API Basics
The Fetch API provides a modern way to make HTTP requests. fetch() returns a Promise that resolves to the Response object.
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) throw new Error("HTTP error " + response.status);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch error:", error));
Try it Yourself โ
GET Request
By default, fetch makes a GET request. Parse the response with .json() or .text().
async function getPosts() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const post = await res.json();
console.log("Title:", post.title);
console.log("Body:", post.body);
} catch (error) {
console.error("Error:", error);
}
}
getPosts();
Try it Yourself โ
POST Request
Send data with a POST request by specifying method, headers, and a JSON body.
async function createPost() {
const newPost = {
title: "New Post",
body: "This is the content",
userId: 1
};
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newPost)
});
const data = await res.json();
console.log("Created:", data);
}
createPost();
Try it Yourself โ