Interview Questions

10 Common Interview Questions on Designing Good RESTful APIs

Author: Interview Questions Posted 5 days ago 46 min read

Designing a clean, scalable, and intuitive RESTful API is a staple topic in backend and system design interviews. Below are 10 of the most frequently asked interview questions on RESTful API design, complete with clear explanations and practical examples.


1. What are the core architectural constraints of a RESTful API?

REST (Representational State Transfer) is an architectural style defined by six constraints:

  • Client-Server Separation: Decouples the user interface (client) from data storage and business logic (server), allowing both to evolve independently.
  • Statelessness: Every request from a client must contain all the information needed to process it (e.g., authentication tokens, parameters). The server does not store client session state between requests, which makes horizontal scaling straightforward.
  • Cacheability: Responses must explicitly declare whether they are cacheable or non-cacheable (using headers like Cache-Control and ETag) to improve performance and reduce server load.
  • Uniform Interface: Standardizes communication through resource identification via URIs, manipulation via representations (like JSON), self-descriptive messages, and HATEOAS.
  • Layered System: Allows intermediaries (such as load balancers, API gateways, and proxies) between the client and server without the client needing to know whether it is connected directly to the end server.
  • Code-on-Demand (Optional): Servers can temporarily extend client functionality by transferring executable code (e.g., JavaScript).


2. How should you design and name RESTful endpoints?

Endpoints should be resource-oriented, modeling business entities rather than actions:

  • Use nouns, not verbs: Let HTTP methods (GET, POST, PUT, DELETE) express the action.
    • Good: GET /orders/123
    • Avoid: GET /getOrder?id=123
  • Use plural nouns for collections: Keeps naming consistent across collection and item endpoints.
    • Collection: GET /users
    • Single Item: GET /users/42
  • Use lowercase and hyphens (kebab-case): Avoid underscores or camelCase for readability and URL consistency.
    • Good: /shipping-addresses
  • Reflect hierarchy logically (avoid deep nesting): Keep nesting to 1–2 levels maximum.
    • Good: GET /articles/10/comments
    • Avoid: GET /organizations/1/departments/5/teams/8/users/42 (flatten to GET /users/42 instead).

3. What is the difference between POST, PUT, and PATCH?

HTTP Method Purpose Payload Idempotent?
POST Creates a new resource (server assigns the URI). Data for the new resource. No
PUT Replaces an existing resource entirely (or creates it at a client-specified URI). The complete representation of the resource. Yes
PATCH Partially updates an existing resource. Only the fields that need to be modified. Depends on implementation (usually yes when setting absolute values)

Example:

# Replaces the entire user record
PUT /users/42
{ "name": "Alice", "email": "[email protected]", "role": "admin" }

# Updates only the user's role
PATCH /users/42
{ "role": "admin" }

4. What is idempotency, and why does it matter in API design?

An operation is idempotent if making the same request multiple times produces the exact same system state as making it once.

  • Why it matters: Network timeouts and transient failures are inevitable in distributed systems. When a client does not receive a response, it must safely retry the request without accidentally duplicating side effects (like charging a credit card twice).
  • How to handle non-idempotent POST requests: Use an Idempotency-Key header (e.g., a client-generated UUID). The server caches the response keyed to that ID—if a retry arrives with the same key, the server returns the original response without re-executing the operation.

5. Which HTTP status codes should a well-designed API return?

Status codes let clients understand request outcomes without parsing the response body:

  • 200 OK: General success for GET, PUT, or PATCH.
  • 201 Created: Resource successfully created via POST (ideally includes a Location header pointing to the new URI).
  • 204 No Content: Request succeeded, no response body needed (common for DELETE).
  • 400 Bad Request: Malformed syntax or invalid request parameters.
  • 401 Unauthorized: Missing or invalid authentication credentials.
  • 403 Forbidden: Authenticated user lacks permission to access the resource.
  • 404 Not Found: Requested resource does not exist.
  • 409 Conflict: Request conflicts with the current resource state (e.g., duplicate email or version mismatch).
  • 422 Unprocessable Entity: Syntactically valid JSON, but fails domain/business validation rules.
  • 429 Too Many Requests: Client exceeded rate limits (include a Retry-After header).
  • 500 Internal Server Error: Unexpected server-side failure.

6. How do you handle API versioning without breaking existing clients?

Once external clients consume an API, breaking changes (removing fields, renaming keys, altering types) require versioning:

  1. URI Path Versioning (Most Common): GET /api/v1/products — Explicit, easy to route, cache, and test in a browser.
  2. Header Versioning: GET /api/products with API-Version: 2 — Keeps URIs clean, though slightly harder to test manually.
  3. Media Type / Content Negotiation: Accept: application/vnd.company.product.v2+json — Most aligned with pure REST principles, but adds complexity for clients.

Best Practice: Favor backward-compatible additive changes (adding optional fields) whenever possible so you only bump major versions when truly necessary.


7. What are the best strategies for pagination on large collections?

Returning unbounded lists causes high latency, memory spikes, and database strain. Two primary strategies solve this:

  • Offset-Based Pagination (?page=2&limit=20 or ?offset=20&limit=20):
    • Pros: Easy to implement; allows jumping to arbitrary page numbers.
    • Cons: Slow on deep pages (OFFSET 100000 still scans skipped rows) and suffers from skipped/duplicated items when records are inserted or deleted between requests.
  • Cursor-Based (Keyset) Pagination (?cursor=eyJpZCI6MTAwfQ&limit=20):
    • Pros: Constant $O(1)$ index lookup performance regardless of dataset size; immune to data drift in real-time feeds.
    • Cons: Cannot jump directly to a specific page number.

8. How should filtering, sorting, and field selection be designed?

Keep resource URIs clean by passing query parameters for collection manipulation:

  • Filtering: Use field names directly as query parameters: GET /orders?status=shipped&customer_id=99
  • Sorting: Use a sort parameter with prefixes (- for descending) or explicit direction: GET /orders?sort=-created_at,total_amount
  • Sparse Fieldsets (Field Selection): Allow clients to request only needed fields to reduce payload size: GET /users?fields=id,name,email

9. How do you design a consistent, developer-friendly error response format?

Never return raw stack traces or inconsistent error shapes. Adopt a standardized schema (such as RFC 9457 / RFC 7807 Problem Details for HTTP APIs):

{
  "type": "[https://api.example.com/errors/insufficient-funds](https://api.example.com/errors/insufficient-funds)",
  "title": "Insufficient Funds",
  "status": 422,
  "detail": "Account balance ($45.00) is lower than the requested transfer ($100.00).",
  "instance": "/transfers/tx_98765",
  "errors": [
    {
      "field": "amount",
      "code": "BALANCE_EXCEEDED",
      "message": "Amount exceeds available balance."
    }
  ]
}

Key elements include a machine-readable error code (so clients don't rely on brittle string matching), a human-readable explanation, and field-level validation details.


10. How do you secure and protect a RESTful API in production?

  • Enforce HTTPS (TLS) everywhere: Encrypts credentials, tokens, and payloads in transit.
  • Stateless Authentication & Authorization: Use short-lived tokens (e.g., JWTs or opaque OAuth 2.0 bearer tokens). Always distinguish between Authentication (401 — who you are) and Authorization (403 — what you are allowed to do, preventing IDOR/broken object-level authorization).
  • Rate Limiting & Throttling: Protect backend services from abuse and traffic spikes using token-bucket or sliding-window algorithms at the API gateway, returning 429 Too Many Requests along with X-RateLimit-* headers.
  • Strict Input Validation & Payload Limits: Validate schemas, sanitize inputs, and enforce maximum request body sizes to prevent injection and denial-of-service attacks.