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/123or URI path/books/123.Endpoint — a URI plus the supported HTTP method (for example,
GET /booksis 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).
- Create ->
REST constraints (exact list used in exam answers) — From Roy Fielding's dissertation, the architectural constraints that characterize a RESTful system are:
- Client–Server (separation of concerns between client and server)
- Stateless (each request from client to server must contain all information to understand the request)
- Cacheable (responses must define themselves as cacheable or not to improve performance)
- 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)
- Layered System (architecture composed of hierarchical layers by constraining component behavior)
- 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 Createdwhen a new resource is created and include aLocationheader;204 No Contentfor successful DELETE when no body is returned;400 Bad Requestfor validation errors;401 Unauthorizedwhen authentication needed/failed;403 Forbiddenfor authenticated but not allowed;404 Not Foundfor missing resource;409 Conflictfor concurrent-update conflicts;500family for server errors.Headers and content negotiation — clients send
Acceptto indicate preferred representation (for exampleapplication/json). Servers setContent-Typeon responses. UseAuthorization: Bearer <token>for bearer tokens. For 401 responses with bearer auth, include aWWW-Authenticatechallenge header. If the requestContent-Typeis unsupported, return415 Unsupported Media Type; if none of the client'sAccepttypes are available, return406 Not Acceptable. UseETagwithIf-None-Matchfor caching (return304 Not Modified), andETagwithIf-Matchfor optimistic concurrency (return412 Precondition Failedon 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 Requestswhen 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):
- Identify resource: book with fields: id (UUID), title (string), author (string), published_year (int).
- URIs: Use plural nouns:
/v1/books(collection),/v1/books/{id}(single resource). - Endpoints and sample request/response:
- Create (POST):
Request:
POST /v1/bookswith headerContent-Type: application/jsonand body:{"title":"Calculus I","author":"Rao","published_year":2015}Server action: validate payload, create book with idb123. Response:201 Createdwith headerLocation: /v1/books/b123and body:{"id":"b123","title":"Calculus I","author":"Rao","published_year":2015} - Read (GET collection):
Request:
GET /v1/books?page=1&per_page=10Response:200 OKbody with array of book representations and paging metadata. - Read (GET single):
Request:
GET /v1/books/b123Response:200 OKwith JSON body for the book or404 Not Foundif missing. - Update (PUT):
Request:
PUT /v1/books/b123with full JSON representation. If provided, replace stored resource. Return200 OKwith updated body. - Partial update (PATCH):
Request:
PATCH /v1/books/b123with{"published_year":2016}. Server applies change and returns200 OKor204 No Content. - Delete (DELETE):
Request:
DELETE /v1/books/b123Response:204 No Contenton success.
- Create (POST):
Request:
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:
- Without idempotency key: first POST creates order
o1. Retry POST creates another ordero2. Duplicate side effects. - With idempotency: client sends header
Idempotency-Key: 111-222-333on first POST. Server stores result keyed by idempotency key. Retry with same key returns same response (HTTP201 CreatedwithLocation: /orders/o1) and does not createo2.
Put vs Post idempotency example:
PUT /users/abcwith same body repeated should result in the same stored resource; the second identical PUT changes nothing (idempotent).POST /userscreates new user each time (non-idempotent) unless an idempotency key is used.
Common mistakes
- Using
PUTfor partial updates (should usePATCH) or misunderstanding idempotency forPATCH. - 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
- Which HTTP method is idempotent and used for full replacement of a resource?
- What status code should a server return when a new resource is successfully created?
- 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?