The Fetch API
Learn how to make HTTP requests directly from JavaScript using the modern Fetch API: retrieve data, send payloads, and handle responses with Promises.
What Is the Fetch API?
The Fetch API is a built-in browser interface that lets your JavaScript code send HTTP requests to servers and receive responses: all without reloading the page. It replaced the older XMLHttpRequest pattern and returns Promises, making asynchronous code cleaner and easier to read.
The Request-Response Cycle
Your code calls fetch(url), which sends an HTTP request to the server. The server processes it and sends back a response. Because network calls are asynchronous, fetch() returns a Promise that resolves when the response arrives.
Promises and async/await
A Promise is an object that represents a value that may not be available yet. It can be in one of three states:
The Core fetch() Syntax
Inside the Response Object
When the Promise resolves, you receive a Response object with several useful properties and methods:
.then() Chains vs async/await
| .then() Chain | async/await | |
|---|---|---|
| Readability | Nested callbacks can be hard to follow | Reads top-to-bottom, like synchronous code |
| Error handling | .catch() at the end of the chain | try/catch blocks wrap the logic |
| Debugging | Stack traces can be confusing | Cleaner stack traces |
| Browser support | All modern browsers | All modern browsers (ES2017+) |
fetch() with async/await
Anatomy of a fetch() Call
Step-by-Step: Making a Request
Example 1: Simple GET Request
Example 2: POST Request
Example 3: Robust Error Handling
HTTP Methods at a Glance
| Method | Purpose | Has Body? |
|---|---|---|
| GET | Read/retrieve data | No |
| POST | Create a new resource | Yes |
| PUT | Update/replace a resource | Yes |
| PATCH | Partially update a resource | Yes |
| DELETE | Remove a resource | Usually no |
Common Mistakes
Fetch API Cheat Sheet
| Task | Code Pattern |
|---|---|
| Simple GET | await fetch(url) |
| Parse JSON | await response.json() |
| Parse Text | await response.text() |
| Send JSON POST | fetch(url, { method: 'POST', headers: {...}, body: JSON.stringify(data) }) |
| Check for errors | if (!response.ok) throw ... |
| Catch network fail | try { ... } catch (err) { ... } |
Question 1 of 5
What does fetch() return?
Question 2 of 5
Which of the following will cause a fetch() Promise to reject?
Question 3 of 5
When sending a POST request with JSON data, which property must be included in the options?
Question 4 of 5
Consider this code:
async function loadData() {
const response = await fetch('/api/items');
const data = await response.json();
const backup = await response.json();
return { data, backup };
}
What happens when loadData() is called?
Question 5 of 5
What is the default HTTP method used by fetch() when no options object is provided?