Errors and async · Lesson 38 of 45
Fetching data from an API
Talk to a server and show the data it sends.
9 minutes2 games
An API is a server address that returns data (usually JSON). fetch(url) sends a request and returns a promise of a response. Check response.ok, then read the body with await response.json().
Browser: fetch(url)
HTTP request (GET)
Server replies: status + JSON
await res.json() → object
JavaScript
async function loadTodo(id) {
try {
const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
if (!res.ok) throw new Error("HTTP " + res.status)
const todo = await res.json()
console.log(`#${todo.id}: ${todo.title}`)
console.log("done?", todo.completed)
} catch (err) {
console.log("Could not load:", err.message)
}
}
loadTodo(1)This is a real free test API. Change the id and run again.
Sending data (POST)
JavaScript
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", body: "From SeaCode", userId: 1 }),
})
const created = await res.json()
console.log(res.status, "created post with id", created.id)| Status | Meaning |
|---|---|
| OK / created |
| bad request |
| not signed in / not allowed |
| not found |
| server error |
Order the lines
Order the steps to fetch data correctly.
- Click the lines in the right order
Quick question
The server replies 404. What does fetch do?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.