JavaScript · Lesson 13 of 15
JSON and the Fetch API
Talk to web APIs: fetch, JSON parsing, headers, POST and error handling.
- Intermediate
- 14 min read
- 3 objectives
Before this lessonLesson 12: Errors and Debugging
What you will learn
- Fetch JSON from an API
- Send a POST request
- Handle HTTP errors
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 3 hours
Create a free account to keep your progress on every device.
Web apps constantly exchange data with servers as JSON. fetch makes the request and returns a promise.
JSON basics
const user = { id: 1, name: "Ada", tags: ["math"] };
const text = JSON.stringify(user);
console.log(text);
console.log(JSON.parse(text).name);
console.log(JSON.stringify(user, null, 2));Output
{"id":1,"name":"Ada","tags":["math"]}
Ada
{
"id": 1,
"name": "Ada",
"tags": [
"math"
]
}JSON keeps only data: functions and undefined are dropped, and dates become strings.
GET request
async function getPost(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch does NOT reject on 404/500
return res.json();
}
getPost(1).then(p => console.log(p.title)).catch(console.error);POST with JSON
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", userId: 1 }),
});
console.log(res.status, await res.json());Several requests, timeouts
const [a, b] = await Promise.all([getPost(1), getPost(2)]); // in parallel
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
await fetch(url, { signal: controller.signal }); // cancel after 5s