REST APIs define a simple but powerful set of rules for how servers and clients communicate over HTTP. The biggest mistake developers make is treating REST as a rigid framework for every design, when it’s really just a set of principles—like keeping interactions stateless or using standardised formats—that you adapt to your needs.
Core Principles
The four pillars of REST are not laws, but if you ignore them, your API will fail to scale, document, or debug easily.
Stateless Design
Each request from a client must contain all the information needed to process it. For example, never rely on cookies or session IDs in headers—include them in query parameters or in the request body.
Why it matters: If you don’t design for statelessness, your app becomes brittle. A stateless API lets third-party tools (like caching layers) work without knowing your backend’s internal state.
Uniform Interface
The seven rules of the uniform interface ensure consistency across all requests:
- Resource Identification in Requests: Use URLs to identify resources (e.g., `/users/123`). Never mix up endpoints with internal database keys.
- Resource-Oriented Design: Organise your API around nouns (users, orders) rather than verbs (getUser, postOrder).
- Standardised Representations: Return data in JSON or XML, with a consistent schema—never mix formats or formats per request.
- HATEOAS: Let clients discover the next possible actions (e.g., links to related endpoints) in the response, rather than hardcoding them.
- Idempotency: Repeating the same request shouldn’t cause unintended side effects (e.g., PUT requests for updating data).
- Safe Methods: GET requests should be safe (no side effects), HEAD for headers-only lookups, and OPTIONS to describe capabilities.
- Cacheable Responses: Indicate if a response can be cached via HTTP headers (e.g., `Cache-Control: max-age=3600`).
If you don’t follow these, your API becomes harder to maintain and harder for clients to write against.
HTTP Methods and Status Codes
Choosing the wrong HTTP method or status code can confuse clients and confuse logs. Here’s how to use them correctly.
When to Use Each Method
- GET: Retrieve a resource (e.g., `/products/42`). Never use GET to modify data.
- POST: Create a new resource (e.g., `/users`). Include the full payload in the body.
- PUT: Replace the entire resource (e.g., `/users/123`). Use idempotent requests only.
- PATCH: Update a subset of the resource (e.g., `/users/123/email`). Never use PUT for partial updates.
- DELETE: Remove a resource (e.g., `/users/123`). Always include the resource ID.
Status Codes Explained
Common codes and their meaning:
| Code | Meaning |
|---|---|
| 200 OK | Request succeeded (GET/PUT/POST). |
| 201 Created | Resource was created (POST). |
| 204 No Content | Success but no response body (e.g., DELETE). |
| 400 Bad Request | Client-side error (invalid format, missing fields). |
| 401 Unauthorized | Authentication failed. |
| 403 Forbidden | Client lacks permission (e.g., missing role). |
| 404 Not Found | Resource doesn’t exist. |
| 500 Internal Server Error | Server-side failure (log this). |
Always include these codes in your API docs to avoid client-side surprises.
Considerations Beyond the Basics
Principles alone won’t make your API work well—you’ll need to apply them with thoughtfulness.
When REST Isn’t Enough
Some designs require alternatives:
- GraphQL: When clients need flexible queries (e.g., fetching only fields they need).
- WebSockets: For real-time updates (e.g., chat apps).
- Graph-Based APIs: If your data is best modelled as a graph (e.g., social networks).
Use REST when you need simplicity, scalability, and broad tooling support.
Performance and Security
Follow these practices to avoid anti-patterns:
- Avoid Caching Sensitively: Use `Cache-Control` headers carefully. Cache GET requests for static data (e.g., images), but avoid caching mutable data (e.g., user profiles).
- Rate-Limit Strategically: Prevent abuse with `Retry-After` headers. Never set a fixed limit without considering human users (e.g., rate limit API calls to 1000/minute for non-business traffic).
- Escape Always: Never trust client input. Validate and sanitise all query parameters, headers, and body data.
- Use HTTPS by Default: Encrypt all communications. If you must support HTTP, limit it to internal services only.
Refactoring Your API
If you’re building a new API or redesigning, here’s how to apply REST principles:
Step-by-Step Refactor
- Audit Your Endpoints: List all resources and methods. Replace poorly named verbs (e.g., `deleteUser` → `/users/123`).
- Standardise Responses: Use JSON with consistent schemas. Include metadata like `ETag`, `Last-Modified`, and `Cache-Control`.
- Enable HATEOAS: Add links to related resources in responses (e.g., `{"next": "/users?offset=10"}`).
- Add Documentation: Document HTTP methods, status codes, and expected payloads. Use tools like Swagger/OpenAPI.
- Test Statelessness: Remove cookies/sessions. Simulate requests without them and ensure they work the same.
What to Check After Refactoring
Validate your changes:
- Can clients fetch data without session data?
- Do all endpoints use GET for retrieval?
- Are responses consistent in format?
- Do all status codes have clear meanings?
Common Pitfalls
Here’s what to watch out for:
Overloading Endpoints
Never combine multiple operations into one endpoint (e.g., `GET /users?role=admin&delete=true`). This violates the uniform interface. Instead:
- Use separate endpoints (e.g., `/users/admin`, `/users/123/delete`).
- Use query parameters for filterable, optional operations (e.g., `?delete=true`).
Ignoring Versioning
Versioning is critical for backward compatibility. Use query parameters (`/v2/users`) or URL segments (`/api/v2/users`). Never change endpoints after deployment.
Skipping Error Handling
Clients expect consistent error messages. Include:
- HTTP status codes.
- Human-readable error details (no database errors).
- A consistent error schema.
Example of a Well-Structured API Endpoint
The following endpoint follows REST principles:
- Endpoint: `/v2/users/{id}/orders`
- Method: GET
- Response: JSON with `orders[]` array, `next` pagination link, and metadata.
- Status Codes: 200 OK, 404 Not Found, 500 Internal Server Error.
- HATEOAS: Response includes a `self` link to fetch more orders.
Quick Reference: REST API Design Rules
| Principle | Rule | Example |
|---|---|---|
| Stateless | No session data in headers | Use query params or headers for auth |
| Uniform Interface | Standardised representations | Always return JSON |
| HTTP Methods | GET = retrieve | Never use GET for updates |
| Cacheable | Use `Cache-Control` headers | Cache GET `/products` for 1 hour |
| HATEOAS | Link to related endpoints | Response includes `/users/123/orders` link |
FAQ
What if I need to send large files? Use chunked uploads with `POST /upload`, implement resumable transfers, and return a `Accept-Ranges: bytes` header. Never use multipart/form-data for large files—it’s inefficient.
Can REST APIs handle real-time data? Yes, but use WebSockets or Server-Sent Events (SSE) alongside REST. REST is not designed for bidirectional updates.
What if my API requires authentication per request? Include credentials in the request body (e.g., JSON web token) or headers (e.g., `Authorization: Bearer token`). Never include them in URLs.
How do I document a REST API? Use OpenAPI/Swagger for machine-readable specs. Document methods, status codes, and example responses. Include a `README.md` with usage examples and error cases.