01 / 21

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.

JavaScript

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

Browser fetch() Your JavaScript Server API Endpoint Returns Data HTTP Request Response (JSON, HTML, etc.) Returns a Promise

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:

Pending
The request has been sent but no response yet. The Promise is still waiting.
Fulfilled
The server responded successfully. The Promise resolves with the data.
Rejected
A network error occurred. The Promise is rejected with an error.

The Core fetch() Syntax

// Basic GET request fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Failed:', error));
1
fetch(url) sends the request and returns a Promise that resolves to a Response object.
2
.then(r => r.json()) parses the response body as JSON (also returns a Promise).
3
.catch() handles any network errors that may occur.

Inside the Response Object

When the Promise resolves, you receive a Response object with several useful properties and methods:

response.ok
Boolean: true if status is 200-299, false otherwise.
response.status
The HTTP status code: 200, 404, 500, etc.
response.json()
Parses body as JSON. Returns a new Promise.
response.text()
Reads body as plain text string. Also returns a Promise.

.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

async function getData() { try { const response = await fetch('https://api.example.com/users'); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } const data = await response.json(); console.log(data); } catch (error) { console.error('Fetch failed:', error); } } getData();

Anatomy of a fetch() Call

fetch( url , options ) url (required) String: the endpoint to call "https://api.example.com/data" options (optional) Object with config keys: method, headers, body, etc. method "GET","POST", ... headers Content-Type, etc. body JSON.stringify(data) mode "cors", "no-cors" Returns: Promise<Response> Resolves when headers arrive

Step-by-Step: Making a Request

1
Choose your URL: identify the API endpoint you need to call (e.g., a REST API path).
2
Pick the method: GET to read data, POST to send data, PUT to update, DELETE to remove.
3
Set headers: if sending JSON, include 'Content-Type': 'application/json'.
4
Add body (for POST/PUT): pass JSON.stringify(data) as the body property.
5
Handle the response: check response.ok, then parse with .json() or .text().
6
Catch errors: wrap in try/catch or add .catch() for network failures.

Example 1: Simple GET Request

// Fetch a list of users and display their names async function showUsers() { const response = await fetch( 'https://jsonplaceholder.typicode.com/users' ); const users = await response.json(); users.forEach(user => { console.log(user.name); }); }

Example 2: POST Request

// Create a new post on the server async function createPost() { const response = await fetch( 'https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'My New Post', body: 'Hello from fetch!', userId: 1 }) } ); const result = await response.json(); console.log('Created:', result); }

Example 3: Robust Error Handling

async function safeFetch(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error( `Server error: ${response.status}` ); } const contentType = response.headers .get('Content-Type'); if (contentType.includes('application/json')) { return await response.json(); } return await response.text(); } catch (error) { console.error('Request failed:', error.message); } }

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

✕ Not checking response.ok
A 404 or 500 still resolves the Promise. Without checking response.ok, your code silently processes error pages as valid data.
✕ Forgetting JSON.stringify()
Passing a plain object as the body sends "[object Object]" to the server. Always wrap it in JSON.stringify().
✕ Missing Content-Type header
Without 'Content-Type': 'application/json', the server may not recognize your JSON payload and return an error.
✕ Calling .json() twice
The response body is a readable stream that can only be consumed once. Calling .json() a second time throws an error.

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

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?