REST API Design
Design RESTful APIs: resource naming, HTTP method semantics, status codes, pagination strategies, versioning, and HATEOAS principles.
REST API design involves resource modeling, correct HTTP semantics, consistent error formats, and pagination. Well-designed REST APIs are predictable, discoverable, and cacheable - making frontend integration and third-party consumption straightforward.
Use noun-based resources in URLs. Match HTTP methods to their correct semantics. Return meaningful status codes. Design for pagination from day one. Standardize error response format. Version via URL path (not headers).
Workflow
- Design resource naming and URL structureConsistent URL structure makes the API predictable and self-documenting.
- Use HTTP methods correctlyCorrect HTTP method semantics enable caching, idempotency, and standard behavior.
- Return correct HTTP status codesCorrect status codes enable clients to handle responses without parsing the body.
- Implement pagination correctlyLarge datasets must be paginated - returning all records is slow and expensive.
- Standardize error responses and versioningInconsistent errors and breaking version changes are the two biggest API usability problems.
Output Format
Noun-based plural URLs, correct HTTP methods/status codes, cursor pagination for feeds, Problem Details error format, URL-path versioning, `Location` header on 201.
Examples
Cursor pagination: `GET /api/v1/posts?limit=20&after=eyJpZCI6MTAwfQ== // Response: { "data": [...], "meta": { "cursor": { "after": "eyJpZCI6MTIwfQ==", "hasMore": true }, "total": 450 } }`RFC 7807 error: `res.status(422).json({ type: "https://api.myapp.com/errors/validation", title: "Validation Failed", status: 422, errors: [{ field: "email", message: "Invalid email format" }] })`PATCH with merge: `PATCH /users/123 Content-Type: application/merge-patch+json { "name": "New Name" } // only name is updated; other fields unchanged`Edge Cases & Gotchas
- Idempotency keys: for POST requests where the client may retry (payment, order creation), support `Idempotency-Key: <uuid>` header - return cached response if same key seen within 24h
- Long-running operations: for tasks that take >1s, return 202 Accepted with a job URL: `{ "jobId": "job_123", "statusUrl": "/api/v1/jobs/job_123" }` - client polls the job URL
- Bulk operations: `DELETE /api/v1/posts` (delete all) is dangerous - require explicit filter `?ids=1,2,3` or `?olderThan=date`
When to Break These Rules
- For real-time collaborative features, REST is the wrong tool - use WebSockets or Server-Sent Events. For mobile clients needing to minimize requests, GraphQL allows fetching exactly the needed data in one request.
Reference Files
REST constraints: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htmRFC 7807 Problem Details: https://www.rfc-editor.org/rfc/rfc7807API design guidelines: https://google.aip.dev/HTTP status codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status