Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

REST API design

Practical, exam-focused notes on REST API design: definitions, REST constraints, mapping CRUD to HTTP, status codes, URL design, headers, idempotency, caching, versioning, security basics, worked examples, common mistakes and quick checks.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineering teams use REST APIs to let clients (web/mobile/frontend) interact with server-side resources. Good REST design makes APIs easy to understand, stable for clients, secure, scalable (works well with API Gateway and Lambda), and simple to test and document.

Key ideas

  • URI (Uniform Resource Identifier) — the string used to identify a resource. Example forms: full URI https://api.example.com/books/123 or URI path /books/123.

  • Endpoint — a URI plus the supported HTTP method (for example, GET /books is an endpoint).

  • HTTP methods: map CRUD to HTTP as follows (exact mapping universities expect):

    • Create -> POST (create a subordinate resource under a collection URI)
    • Read -> GET (retrieve representation)
    • Update (full) -> PUT (replace resource; idempotent)
    • Update (partial) -> PATCH (modify resource; not necessarily idempotent unless defined)
    • Delete -> DELETE (remove resource; idempotent)

    Define idempotent: An operation is idempotent if performing it once or multiple times has the same effect on the server state. Define safe: A method is safe if it does not change server state (GET, HEAD, and OPTIONS are safe).

  • REST constraints (exact list used in exam answers) — From Roy Fielding's dissertation, the architectural constraints that characterize a RESTful system are:

    1. Client–Server (separation of concerns between client and server)
    2. Stateless (each request from client to server must contain all information to understand the request)
    3. Cacheable (responses must define themselves as cacheable or not to improve performance)
    4. Uniform Interface (identification of resources, manipulation through representations, self-descriptive messages, and hypermedia as the engine of application state HATEOAS — optional for many practical REST APIs)
    5. Layered System (architecture composed of hierarchical layers by constraining component behavior)
    6. Code on Demand (optional) (servers can extend client functionality by transferring executable code)

    For each constraint, state the assumption: for example, Statelessness assumes no server-side session used to process a request (all session info must be in token or request).

  • Status codes — use appropriate HTTP status codes to communicate result (details and common choices in Formulas). In particular, 201 Created when a new resource is created and include a Location header; 204 No Content for successful DELETE when no body is returned; 400 Bad Request for validation errors; 401 Unauthorized when authentication needed/failed; 403 Forbidden for authenticated but not allowed; 404 Not Found for missing resource; 409 Conflict for concurrent-update conflicts; 500 family for server errors.

  • Headers and content negotiation — clients send Accept to indicate preferred representation (for example application/json). Servers set Content-Type on responses. Use Authorization: Bearer <token> for bearer tokens. For 401 responses with bearer auth, include a WWW-Authenticate challenge header. If the request Content-Type is unsupported, return 415 Unsupported Media Type; if none of the client's Accept types are available, return 406 Not Acceptable. Use ETag with If-None-Match for caching (return 304 Not Modified), and ETag with If-Match for optimistic concurrency (return 412 Precondition Failed on mismatch).

  • Versioning — do not use headers as the only versioning mechanism in exams unless asked; common safe approach: include version in the path like /v1/books. State the assumption: URI versioning is explicit but may be less REST-pure than media-type versioning.

  • Pagination, filtering, sorting — design query parameters like GET /books?page=2&per_page=20&sort=title&order=asc&author=Kumar. Provide metadata (total count, next/prev links) in response.

  • Idempotency keys for non-idempotent operations — to avoid duplicate side effects from retries, use a client-supplied idempotency key header (for example Idempotency-Key: <uuid>) stored server-side to de-duplicate POSTs. The header name is not standardized; document your choice clearly.

  • Security basics — use HTTPS for transport security, validate inputs, perform authorization checks per resource, avoid returning detailed errors in production. Enable CORS appropriately on API Gateway for browser clients. For AWS integration, API Gateway commonly handles TLS and integrates with Lambda or HTTP backends; use Cognito/JWT authorizers for authentication/authorization (see tracks: API Gateway, Lambda, Amazon Cognito). Apply rate limiting/throttling and return 429 Too Many Requests when limits are exceeded.

  • Diagram to draw (exam requirement): draw a simple labeled diagram with: Client -> API Gateway -> (Auth check) -> Service/Lambda -> Database. Label URIs on the gateway, show stateless arrows, and annotate which components may cache responses.

Formulas

(For programming/web topics, list syntax to remember)

GET /resources — list collection (use query params for pagination/filtering)

GET /resources/{id} — retrieve single resource

POST /resources — create new resource; request body: JSON representation of new resource

PUT /resources/{id} — replace resource with supplied representation (idempotent)

PATCH /resources/{id} — partially update resource (non-idempotent unless defined; use JSON Patch (RFC 6902) or JSON Merge Patch (RFC 7396))

DELETE /resources/{id} — delete resource (idempotent)

HEAD /resources/{id} — like GET but returns headers only (no body); useful for caching and existence checks

OPTIONS /resources — discover supported methods; include an Allow header; used for CORS preflight

Content-Type: application/json — header indicating JSON payload

Accept: application/json — header asking for JSON response

Authorization: Bearer <token> — header for bearer token authentication

Location: /resources/{id} — response header to return with 201 Created

Idempotency-Key: <uuid> — header to deduplicate POST retries (server-side storage required)

Common status codes to remember in answers:

200 OK — successful GET/PUT returning body

201 Created — resource created (include Location header)

204 No Content — success with no body (common for DELETE)

400 Bad Request — client sent malformed request or failed validation

401 Unauthorized — authentication required or failed

403 Forbidden — authenticated but not allowed

404 Not Found — resource does not exist

409 Conflict — resource conflict (optimistic locking failure)

412 Precondition Failed — conditional request failed (e.g., ETag mismatch with If-Match for optimistic concurrency)

422 Unprocessable Entity — semantic validation failed (optional, from WebDAV but commonly used)

405 Method Not Allowed — method not supported on the target resource (include Allow header)

406 Not Acceptable — server cannot produce a response matching the client's Accept header

415 Unsupported Media Type — request payload media type is unsupported

429 Too Many Requests — rate limiting/throttling

202 Accepted — request accepted for processing but not yet completed (use for async operations)

304 Not Modified — cache revalidation success; send no body

500 Internal Server Error — generic server error

Worked examples

Example 1 — Design and request/response for a Books resource (exam-style model answer).

Problem: Design endpoints for a 'books' resource that allows creating, reading, updating and deleting.

Answer (step-by-step):

  1. Identify resource: book with fields: id (UUID), title (string), author (string), published_year (int).
  2. URIs: Use plural nouns: /v1/books (collection), /v1/books/{id} (single resource).
  3. Endpoints and sample request/response:
    • Create (POST): Request: POST /v1/books with header Content-Type: application/json and body: {"title":"Calculus I","author":"Rao","published_year":2015} Server action: validate payload, create book with id b123. Response: 201 Created with header Location: /v1/books/b123 and body: {"id":"b123","title":"Calculus I","author":"Rao","published_year":2015}
    • Read (GET collection): Request: GET /v1/books?page=1&per_page=10 Response: 200 OK body with array of book representations and paging metadata.
    • Read (GET single): Request: GET /v1/books/b123 Response: 200 OK with JSON body for the book or 404 Not Found if missing.
    • Update (PUT): Request: PUT /v1/books/b123 with full JSON representation. If provided, replace stored resource. Return 200 OK with updated body.
    • Partial update (PATCH): Request: PATCH /v1/books/b123 with {"published_year":2016}. Server applies change and returns 200 OK or 204 No Content.
    • Delete (DELETE): Request: DELETE /v1/books/b123 Response: 204 No Content on success.

Example 2 — Idempotency and retries (step-by-step trace):

Scenario: Client sends POST /orders to create an order but network times out. Client retries.

Trace:

  1. Without idempotency key: first POST creates order o1. Retry POST creates another order o2. Duplicate side effects.
  2. With idempotency: client sends header Idempotency-Key: 111-222-333 on first POST. Server stores result keyed by idempotency key. Retry with same key returns same response (HTTP 201 Created with Location: /orders/o1) and does not create o2.

Put vs Post idempotency example:

  • PUT /users/abc with same body repeated should result in the same stored resource; the second identical PUT changes nothing (idempotent).
  • POST /users creates new user each time (non-idempotent) unless an idempotency key is used.

Common mistakes

  • Using PUT for partial updates (should use PATCH) or misunderstanding idempotency for PATCH.
  • Forgetting to validate and escape inputs (security risk).
  • Not designing for pagination — returning huge collections in one response.
  • Putting sensitive data in query strings (they appear in logs); use headers or body for secrets.
  • Not using HTTPS in deployed APIs.
  • Not choosing a consistent versioning scheme or changing URIs in breaking ways without version bump.
  • Returning overly detailed internal error messages in production.

For your exam

Types of questions you will be asked:

  • Definitions: define REST, resource, representation, idempotent, safe.
  • Short notes: explain statelessness, caching, uniform interface.
  • Design question: design endpoints for a resource with examples of request/response and status codes.
  • Derivation/Explanation: map CRUD operations to HTTP methods and justify choices (mention idempotency and safety).
  • Programs/trace: show sequence of HTTP requests for create-read-update-delete and what the server returns.
  • Diagram: draw API Gateway -> Backend -> Database flow and label headers/URIs.

What full-marks answers include:

  • Clear definitions with bold terms.
  • Correct list of REST constraints and assumptions for each.
  • Correct mapping of CRUD to HTTP methods with idempotency and safe explanations.
  • Correct status codes for sample operations and mention of relevant headers (Content-Type, Location, Authorization).
  • Example URIs, request and response bodies (JSON) and a small diagram when asked.

Quick check

  1. Which HTTP method is idempotent and used for full replacement of a resource?
  2. What status code should a server return when a new resource is successfully created?
  3. What header should a client send to authenticate with a bearer token?

Answers: 1) PUT 2) 201 Created (include Location header) 3) Authorization: Bearer <token>

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?