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:

  1. Resource Identification in Requests: Use URLs to identify resources (e.g., `/users/123`). Never mix up endpoints with internal database keys.
  2. Resource-Oriented Design: Organise your API around nouns (users, orders) rather than verbs (getUser, postOrder).
  3. Standardised Representations: Return data in JSON or XML, with a consistent schema—never mix formats or formats per request.
  4. HATEOAS: Let clients discover the next possible actions (e.g., links to related endpoints) in the response, rather than hardcoding them.
  5. Idempotency: Repeating the same request shouldn’t cause unintended side effects (e.g., PUT requests for updating data).
  6. Safe Methods: GET requests should be safe (no side effects), HEAD for headers-only lookups, and OPTIONS to describe capabilities.
  7. 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

  1. GET: Retrieve a resource (e.g., `/products/42`). Never use GET to modify data.
  2. POST: Create a new resource (e.g., `/users`). Include the full payload in the body.
  3. PUT: Replace the entire resource (e.g., `/users/123`). Use idempotent requests only.
  4. PATCH: Update a subset of the resource (e.g., `/users/123/email`). Never use PUT for partial updates.
  5. DELETE: Remove a resource (e.g., `/users/123`). Always include the resource ID.

Status Codes Explained

Common codes and their meaning:

CodeMeaning
200 OKRequest succeeded (GET/PUT/POST).
201 CreatedResource was created (POST).
204 No ContentSuccess but no response body (e.g., DELETE).
400 Bad RequestClient-side error (invalid format, missing fields).
401 UnauthorizedAuthentication failed.
403 ForbiddenClient lacks permission (e.g., missing role).
404 Not FoundResource doesn’t exist.
500 Internal Server ErrorServer-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:

  1. GraphQL: When clients need flexible queries (e.g., fetching only fields they need).
  2. WebSockets: For real-time updates (e.g., chat apps).
  3. 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

  1. Audit Your Endpoints: List all resources and methods. Replace poorly named verbs (e.g., `deleteUser` → `/users/123`).
  2. Standardise Responses: Use JSON with consistent schemas. Include metadata like `ETag`, `Last-Modified`, and `Cache-Control`.
  3. Enable HATEOAS: Add links to related resources in responses (e.g., `{"next": "/users?offset=10"}`).
  4. Add Documentation: Document HTTP methods, status codes, and expected payloads. Use tools like Swagger/OpenAPI.
  5. 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:

  1. Endpoint: `/v2/users/{id}/orders`
  2. Method: GET
  3. Response: JSON with `orders[]` array, `next` pagination link, and metadata.
  4. Status Codes: 200 OK, 404 Not Found, 500 Internal Server Error.
  5. HATEOAS: Response includes a `self` link to fetch more orders.

Quick Reference: REST API Design Rules

PrincipleRuleExample
StatelessNo session data in headersUse query params or headers for auth
Uniform InterfaceStandardised representationsAlways return JSON
HTTP MethodsGET = retrieveNever use GET for updates
CacheableUse `Cache-Control` headersCache GET `/products` for 1 hour
HATEOASLink to related endpointsResponse 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.