Asynchronous JavaScript and the Fetch APILesson 4.4
How to fetch data from an API using the Fetch API
fetch function, Request, Response object, response.ok, response.json, response.text, HTTP methods, Content-Type header
The Fetch API
fetch() is the browser's built-in function for making HTTP requests. It returns a Promise that resolves to a Response object.
async function getUsers() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
const users = await res.json(); // second await!
return users;
}Always Check res.ok
fetch only rejects on network errors (no connection). A 404 or 500 response resolves successfully — you must check res.ok or res.status manually.
POST Request
const res = await fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Hello', body: 'World' })
});
const created = await res.json();res.json() Returns a Promise
res.json() reads the response stream and parses it — this is asynchronous and must be awaited. Forgetting the second await is a very common bug.
