Consuming REST APIs · Lesson 13 of 30
Calling REST APIs with JavaScript fetch
Calling an API looks like one line: await fetch(url). Calling it reliably is a different matter – networks drop, servers time out, rate limits kick in, and a 500 doesn't throw. This lesson builds a small, production-style API client with fetch, which works the same in browsers, Node.js 18+, Deno and Bun.
In this lesson
- GET and POST with fetch
- Why fetch doesn't throw on 404 or 500
- Timeouts with AbortSignal
- Retries with exponential backoff – only when safe
The API we'll call
This test server is deliberately unreliable: the first two calls to /api/quote fail with 503, and /api/slow takes three seconds.
// server.js
import express from 'express';
const app = express();
app.use(express.json());
let quoteCalls = 0;
app.get('/api/quote', (req, res) => {
quoteCalls++;
if (quoteCalls <= 2) return res.status(503).set('Retry-After', '1').json({ error: 'Service busy' });
res.json({ symbol: 'LFRZ', price: 412.5, attempt: quoteCalls });
});
app.get('/api/slow', async (req, res) => {
await new Promise((r) => setTimeout(r, 3000));
res.json({ ok: true });
});
app.post('/api/orders', (req, res) => {
if (!req.body?.symbol) return res.status(422).json({ error: 'symbol is required' });
res.status(201).json({ id: 'ord_77', ...req.body });
});
app.listen(process.env.PORT ?? 3000);
A reliable client
// apiClient.js
export class ApiError extends Error {
constructor(status, body) {
super(`HTTP ${status}: ${body?.error ?? 'request failed'}`);
this.status = status;
this.body = body;
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
export async function request(url, { method = 'GET', body, timeoutMs = 2000, retries = 3, log = () => {} } = {}) {
const idempotent = ['GET', 'HEAD', 'PUT', 'DELETE'].includes(method); // only these are safe to repeat
for (let attempt = 1; ; attempt++) {
try {
const res = await fetch(url, {
method,
headers: { Accept: 'application/json', ...(body ? { 'Content-Type': 'application/json' } : {}) },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(timeoutMs), // give up if the server is too slow
});
const data = res.status === 204 ? null : await res.json().catch(() => null);
if (res.ok) return data; // fetch does NOT throw for 4xx/5xx – check ok
if (idempotent && RETRYABLE.has(res.status) && attempt <= retries) {
const wait = Number(res.headers.get('Retry-After')) * 1000 || 200 * 2 ** (attempt - 1);
log(`attempt ${attempt}: ${res.status}, retrying in ${wait} ms`);
await sleep(wait);
continue;
}
throw new ApiError(res.status, data);
} catch (err) {
if (err.name === 'TimeoutError') {
log(`attempt ${attempt}: timed out after ${timeoutMs} ms`);
if (idempotent && attempt <= retries) continue;
throw new ApiError(504, { error: 'timeout' });
}
throw err;
}
}
}
// client.js
import { request, ApiError } from './apiClient.js';
const API = 'http://localhost:3000';
const quote = await request(`${API}/api/quote`, { log: console.log });
console.log('quote:', quote);
const order = await request(`${API}/api/orders`, { method: 'POST', body: { symbol: 'LFRZ', qty: 5 } });
console.log('created:', order);
try {
await request(`${API}/api/orders`, { method: 'POST', body: {} });
} catch (err) {
if (err instanceof ApiError) console.log('validation failed:', err.status, err.body.error);
}
try {
await request(`${API}/api/slow`, { timeoutMs: 500, retries: 1, log: console.log });
} catch (err) {
console.log('gave up:', err.message);
}
$ node client.js
attempt 1: 503, retrying in 1000 ms
attempt 2: 503, retrying in 1000 ms
quote: { symbol: 'LFRZ', price: 412.5, attempt: 3 }
created: { id: 'ord_77', symbol: 'LFRZ', qty: 5 }
validation failed: 422 symbol is required
attempt 1: timed out after 500 ms
attempt 2: timed out after 500 ms
gave up: HTTP 504: timeoutWhat the client did
- 503, 503retryable and GET is idempotent: waited Retry-After (1 s) each time
- 200third attempt succeeded
- POST 201 / 422no retries for POST; the 422 became a typed ApiError
- Timeoutsaborted after 500 ms, retried once, then gave up with a clear error
The rules behind it
- Check
res.ok. fetch only rejects on network failure; a 404 or 500 resolves normally. - Always set a timeout. Without one, a hung server can block a request forever.
AbortSignal.timeout(ms)is built in. - Retry only what's safe. Retry idempotent requests on 408/429/5xx and network errors. Never blindly retry POST – you could create duplicate orders or payments (unless you use an idempotency key, covered later).
- Back off. Wait longer each time (exponential backoff, ideally with random jitter), and honour
Retry-After, so thousands of clients don't hammer a recovering server at once. - Keep it in one place. A small client module handles base URLs, auth headers, JSON, errors and retries for the whole app.
In the browser
The same code works in a browser, but the server must allow your site's origin with CORS (covered in the security chapter). Never put secret API keys in browser code – call third-party APIs through your own backend.
Practice
Try it yourself
Fetch two endpoints in parallel and report both results, even if one fails.
Show solution
// server.js import express from 'express'; const app = express(); app.get('/api/user', (req, res) => res.json({ name: 'Asha' })); app.get('/api/notifications', (req, res) => res.status(500).json({ error: 'down' })); app.listen(process.env.PORT ?? 3000);// client.js const API = 'http://localhost:3000'; const results = await Promise.allSettled( ['/api/user', '/api/notifications'].map(async (path) => { const res = await fetch(API + path, { signal: AbortSignal.timeout(2000) }); if (!res.ok) throw new Error(`${path} → ${res.status}`); return res.json(); }) ); for (const r of results) console.log(r.status, r.status === 'fulfilled' ? r.value : r.reason.message);$ node client.js fulfilled { name: 'Asha' } rejected /api/notifications → 500
Quick check
Does fetch throw on a 500 response?
No – check res.ok or res.status.
Should a client retry a failed POST /payments automatically?
Not without an idempotency key – it could charge twice.
What should a client do with Retry-After?
Wait at least that long before retrying.
Summary
- fetch resolves for HTTP errors – always check res.ok and parse errors into typed exceptions.
- Set timeouts with AbortSignal.timeout; retry idempotent requests with backoff and Retry-After.
- Centralise base URL, headers, errors and retries in one client module.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.