JavaScript · Lesson 30 / 32 · English
Fetch API
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
fetch returns a promise for a Response. Check response.ok before reading the body. This example fetches a local data URL, so it demonstrates the response flow without depending on a third-party endpoint.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
The Fetch API
The Fetch API provides a modern, promise-based way to make HTTP requests in the browser. It replaced the older XMLHttpRequest (XHR).
GET Request
// Basic GET request
async function getPost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const post = await response.json();
return post;
}
const post = await getPost(1);
console.log(post.title);POST, PUT, DELETE Requests
// POST — create new resource
async function createPost(data) {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer your-token"
},
body: JSON.stringify(data)
});
return response.json();
}
// PUT — update (full replacement)
async function updatePost(id, data) {
const res = await fetch(`/api/posts/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
return res.json();
}
// DELETE
async function deletePost(id) {
const res = await fetch(`/api/posts/${id}`, { method: "DELETE" });
return res.ok;
}Request Options & Headers
const response = await fetch("/api/data", {
method: "GET",
headers: new Headers({
"Accept": "application/json",
"Authorization": `Bearer ${token}`
}),
// mode: "cors", // cors, no-cors, same-origin
// cache: "no-store", // default, no-store, reload, no-cache, force-cache
// credentials: "include", // include cookies cross-origin
signal: AbortSignal.timeout(5000) // cancel after 5s
});
// Response inspection
console.log(response.status); // 200
console.log(response.ok); // true (200-299)
console.log(response.statusText); // "OK"
console.log(response.headers.get("content-type"));
// Reading the body (can only be read once)
const json = await response.json(); // parse as JSON
const text = await response.text(); // raw text
const blob = await response.blob(); // binary data
const buffer = await response.arrayBuffer();A complete example
Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.
async function loadCourse() {
const url = "data:application/json," + encodeURIComponent(JSON.stringify({title:"JavaScript", lessons:32}));
const response = await fetch(url);
if (!response.ok) throw new Error("HTTP " + response.status);
const course = await response.json();
console.log(course.title);
console.log(course.lessons);
}
loadCourse().catch(error => console.log(error.message));Predict first. Reveal the expected result.
JavaScript 32
Make one change. See what happens.
Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Change lessons to 40 in the data passed to JSON.stringify.
Reveal the answer and reasoning
The second output becomes 40. For a real API, replace the URL and retain the status check and error handling.
One mistake to avoid: fetch does not reject just because an HTTP response has status 404 or 500. Cross-origin requests can also be blocked by CORS; never put secret API keys in browser code.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.