APIs & Integrations
REST APIs
REST (Representational State Transfer) is the dominant API style for web services. Master HTTP methods, status codes, resource design, the Fetch API, error handling, timeouts, retries, pagination, and building reusable API clients.
What is a REST API?
A REST API exposes data as resources at URLs (/api/users/42) and uses HTTP methods to act on them: GET to read, POST to create, PUT or PATCH to update, and DELETE to remove. Responses use status codes (200 OK, 201 Created, 404 Not Found, 500 Server Error) and usually JSON bodies. From JavaScript you call REST APIs with fetch.
GET /api/posts → list
GET /api/posts/42 → one post
POST /api/posts → create (body: JSON)
PATCH /api/posts/42 → partial update
DELETE /api/posts/42 → delete
const res = await fetch("/api/posts/42", { method: "DELETE" });HTTP Methods Reference
| Method | Path | Status | Body | Idempotent? | Action |
|---|---|---|---|---|---|
| GET | /posts | 200 | — | Yes | List all posts |
| GET | /posts/1 | 200/404 | — | Yes | Get single post |
| POST | /posts | 201 | JSON | No | Create new post |
| PUT | /posts/1 | 200 | Full JSON | Yes | Replace entire post |
| PATCH | /posts/1 | 200 | Partial JSON | Yes | Update specific fields |
| DELETE | /posts/1 | 204 | — | Yes | Delete post |
Common Pitfalls
Not checking res.ok after fetch() — fetch only throws on network error, not HTTP 4xx/5xx
Always: if (!res.ok) throw new Error(res.statusText). Fetch resolves even on 404/500. You must check ok or status.
Sending sensitive data in GET query params — logged in servers, proxies, browser history
Use POST with a JSON body for sensitive data. GET params appear in URLs, server logs, and Referer headers.
No request timeout — fetch hangs forever on slow/unresponsive servers
Wrap with AbortController + setTimeout: abort after N seconds. Always provide a timeout for production code.
Mutating UI state directly in multiple fetch calls — race condition: old response arrives after new one
Use AbortController to cancel stale requests. In React: track request ID and ignore stale responses.
Interactive Demo
Code Editor
<button id="list">GET /posts</button>
<button id="create">POST /posts</button>
<button id="del">DELETE /posts/1</button>
<pre id="out"></pre>Preview
REST APIs: summary
Key points
- Use nouns for URLs (
/users), not verbs (/getUsers). - Use 4xx status codes for client errors and 5xx for server errors.
- Paginate large lists (
?page=2&limit=20or cursors). GETrequests must not change data.
Frequently asked questions
›What is the difference between PUT and PATCH?
PUT replaces the whole resource with what you send. PATCH updates only the fields you send.