Skip to content

Interview PrepREST API design · Core

REST Fundamentals ​

42. What is REST, and what constraints define a RESTful API? ​

The short answer

REST, representational state transfer, is an architectural style for networked applications described by Roy Fielding in 2000. Its central idea is resources, such as orders or customers, each identified by a URL and manipulated through a small, uniform set of operations, the HTTP methods, by exchanging representations such as JSON. Its constraints are a client-server split, statelessness, cacheability, a uniform interface, a layered system and, optionally, code on demand. In practice, "RESTful" usually means resource-oriented URLs, correct HTTP methods and status codes, and JSON.

ConstraintMeaningWhat it gives you
Client-serverUI and data storage are separateEach side changes independently
StatelessEach request carries everything needed; no session state on the server between requestsAny server can handle any request: easy scaling
CacheableResponses say whether and how long they can be cachedLess load, faster clients
Uniform interfaceResources by URL, standard methods, self-describing messages, linksOne way to use every resource
Layered systemClients cannot tell whether they talk to the server or a proxyLoad balancers, caches and gateways in between
Code on demand, optionalServers may send code, such as JavaScriptRarely used in APIs

Stateless, the constraint interviewers probe. It does not mean "no database". It means the server does not keep per-client conversation state between requests in its own memory. Each request carries its own authentication, such as a token or a session cookie that points to a shared store, so request 2 can go to a different server than request 1.

What a RESTful design looks like:

http
GET    /orders?status=paid        list orders
POST   /orders                    create an order
GET    /orders/ord_42             read one
PATCH  /orders/ord_42             change part of it
DELETE /orders/ord_42             cancel or delete it
GET    /orders/ord_42/items       a sub-collection

REST is not the only choice. GraphQL lets clients ask for exactly the fields they need in one query, and gRPC offers fast, typed calls between services. The comparison is in the architecture module.

43. What is CRUD, and how does it map to HTTP methods? ​

The short answer

CRUD stands for create, read, update and delete, the four basic operations on stored data. In a REST API they map to HTTP methods: create is POST to a collection, read is GET, update is PUT for a full replacement or PATCH for a partial change, and delete is DELETE. The mapping is a good starting point, but real APIs also have actions that are not plain CRUD, such as "cancel an order" or "send a password reset", which are modelled as sub-resources or POST actions.

CRUDHTTPURLSuccess status
CreatePOST/products201 Created
Read manyGET/products?category=tea200 OK
Read oneGET/products/tea-earl-grey200 OK
Update allPUT/products/tea-earl-grey200 OK
Update partPATCH/products/tea-earl-grey200 OK
DeleteDELETE/products/tea-earl-grey204 No Content

Actions that do not fit CRUD:

ActionCommon REST shape
Cancel an orderPOST /orders/ord_42/cancellation, or PATCH /orders/ord_42 with { "status": "cancelled" }
Send a password reset emailPOST /password-resets
Retry a failed paymentPOST /payments/pay_9/retries

Modelling actions as creating a resource, such as "a cancellation", keeps the API consistent and gives each action its own URL, status and history.

44. What HTTP status codes should a well-designed REST API use? ​

The short answer

Use the standard meanings, so clients can react without reading your docs. 2xx means success: 200 OK, 201 Created with a Location header, 202 Accepted for work queued for later, and 204 No Content. 4xx means the client must change something: 400 bad input, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict, 422 well-formed but invalid, 429 too many requests. 5xx means the server failed: 500 unexpected error, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.

CodeMeaningExample
200 OKSuccess, with a bodyGET /orders/ord_42
201 CreatedA resource was createdPOST /orders, plus Location: /orders/ord_42
202 AcceptedAccepted, will be done laterExport queued
204 No ContentSuccess, no bodyDELETE /cart/items/tea
304 Not ModifiedCached copy is still validConditional GET (question 55)
400 Bad RequestMalformed or invalid inputMissing required field
401 UnauthorizedNot authenticated: who are you?Missing or expired token
403 ForbiddenAuthenticated, not allowedA customer calling an admin endpoint
404 Not FoundNo such resource, or hidden from youUnknown order ID
405 Method Not AllowedWrong method for this URLDELETE /orders
409 ConflictClashes with current stateEmail already registered, stale version
412 Precondition FailedIf-Match did not matchOptimistic concurrency (question 56)
413 Content Too LargeBody too large50 MB upload to a 5 MB endpoint
415 Unsupported Media TypeWrong Content-TypeXML sent to a JSON API
422 Unprocessable ContentSyntax fine, meaning invalidDelivery date in the past
429 Too Many RequestsRate limited, with Retry-AfterToo many login attempts
500 Internal Server ErrorUnexpected failureA bug
502 Bad GatewayAn upstream service sent a bad responsePayment provider returned garbage
503 Service UnavailableTemporarily down or overloadedMaintenance, with Retry-After
504 Gateway TimeoutAn upstream service did not answer in timeInventory service timed out

401 versus 403, the classic interview question: 401 means "I do not know who you are", so sign in; 403 means "I know who you are, and you may not do this", so signing in again will not help.

400 versus 422: many APIs use 400 for every input problem, which is fine. Others use 400 for malformed requests, such as invalid JSON, and 422 for valid JSON that breaks business rules. Pick one convention and use it everywhere.

The anti-pattern: 200 OK with { "success": false } in the body. Clients, proxies, monitoring and retries all rely on the status code.

45. What is idempotency, and which HTTP methods are idempotent? ​

The short answer

An operation is idempotent if doing it several times has the same effect on the server as doing it once. GET, HEAD, OPTIONS, PUT and DELETE are defined as idempotent: setting a resource to the same value twice, or deleting it twice, leaves the same state. POST is not: two POST /orders calls create two orders. PATCH may or may not be, depending on the change. Idempotency matters because networks fail, and a client that never saw a response must know whether it can safely retry.

MethodSafe, no changesIdempotentRetry blindly?
GET, HEAD, OPTIONSYesYesYes
PUTNoYesYes
DELETENoYesYes
PATCHNoDependsOnly if the change is a "set"
POSTNoNoOnly with an idempotency key (question 46)

Same effect, not same response. Deleting an order twice: the first call returns 204, the second may return 404. That is still idempotent, because the server's state, "order deleted", is the same after one call or two.

PATCH in practice:

json
{ "status": "shipped" }                     idempotent: sets a value
{ "op": "increment", "field": "qty" }       not idempotent: adds each time

Idempotency is a promise you must keep in code. Declaring PUT idempotent means your handler must not, for example, send a "your order changed" email every time it is called with the same data.

46. What are idempotency keys, and how do they prevent duplicate operations? ​

The short answer

An idempotency key is a unique value, usually a UUID, that the client generates for one logical operation and sends in a header, such as Idempotency-Key, with a POST request. The server stores the key together with the result of the first request. If the same key arrives again, for example because the client retried after a timeout, the server returns the stored result instead of performing the operation again. Payment providers such as Stripe use this so a retried charge never bills a customer twice.

clientkey K1 =7f3e…APIkey storeK1 → 201, order 42① POST, K1② new: save③ reply lost④ retry, K1⑤ seen: reuse⑥ same 201
The same key gets the same answer. ① The client sends the order with a key. ② The server performs it and saves the result under that key. ③ The reply is lost. ④ The client retries with the same key. ⑤ The server finds the key. ⑥ It returns the saved result, and no second order is created.
ts
app.post('/orders', authenticate, async (req, res) => {
  const key = req.get('Idempotency-Key')
  if (!key) return res.status(400).json({ type: 'idempotency_key_required' })

  const scope = `${req.user!.id}:${key}`                                        // (1)
  const fingerprint = hash(JSON.stringify(req.body))

  const existing = await idempotency.find(scope)
  if (existing) {
    if (existing.fingerprint !== fingerprint) return res.status(422).json({ type: 'key_reused_with_different_body' })   // (2)
    if (existing.status === 'in_progress') return res.status(409).json({ type: 'request_in_progress' })               // (3)
    return res.status(existing.responseStatus).json(existing.responseBody)                                            // (4)
  }

  await idempotency.reserve(scope, fingerprint)                                // (5) unique constraint on scope
  const order = await orders.create(req.user!.id, CreateOrder.parse(req.body))
  await idempotency.complete(scope, 201, order)                                // (6)
  res.status(201).json(order)
})
  1. Scope keys per user, so one user's key can never return another user's result.
  2. Same key, different body is a client bug; refuse it rather than guess.
  3. The first request is still running: tell the client to wait and retry.
  4. Already done: return the stored result, byte for byte.
  5. Reserve the key first, protected by a unique database constraint, so two retries arriving at the same moment cannot both pass the check.
  6. Store the final response for later retries; keep it for a set period, such as 24 hours.

Where to use them: any POST with real-world effects: payments, orders, transfers, sending messages. The same idea makes message consumers safe against duplicate deliveries (the retries in event-driven code question).

47. How should API resource URIs be named? ​

The short answer

Name resources with nouns, not verbs, because the HTTP method already says what happens: /orders, not /getOrders. Use plural nouns for collections, with an ID for one item, /orders/ord_42. Use lower case and hyphens, /gift-cards. Show relationships with nesting, but only one or two levels deep, /customers/c17/orders. Put filters, sorting and paging in the query string, not the path, and keep the style identical across the whole API.

GoodAvoidWhy
GET /ordersGET /getAllOrdersThe method is the verb
GET /orders/ord_42GET /order?id=42Path for identity, query for options
POST /ordersPOST /orders/createPOST to a collection already means create
/gift-cards/giftCards, /Gift_CardsConsistent, readable, case-safe
/customers/c17/orders/customers/c17/orders/ord_42/items/3/notes/9Deep nesting becomes rigid
/orders?status=paid&sort=-createdAt/orders/paid/sorted-by-dateFilters are options

IDs in URLs: prefer opaque, non-guessable IDs, such as ord_8f3k2… or UUIDs, over sequential numbers, which reveal how many orders you have and make it easy to try the next one (the authorisation middleware question).

When nesting stops helping: if an order item can be addressed on its own, give it a top-level path too, such as /order-items/item_9, rather than forcing clients to know its parent.

48. What is the Richardson Maturity Model? ​

The short answer

The Richardson Maturity Model, described by Leonard Richardson and popularised by Martin Fowler, grades how fully an API uses the web's ideas, in four levels. Level 0 sends everything to one URL, usually with POST, like remote procedure calls over HTTP. Level 1 introduces separate resources with their own URLs. Level 2 adds proper use of HTTP methods and status codes. Level 3 adds hypermedia, HATEOAS: responses include links to what the client can do next. Most good public APIs are at level 2.

LevelNameExample
0One endpoint, RPC stylePOST /api with { "action": "getOrder", "id": 42 }
1ResourcesPOST /orders/42 with { "action": "get" }
2HTTP methods and status codesGET /orders/42 → 200, or 404
3Hypermedia controlsResponses include links such as "cancel": "/orders/42/cancellation" (question 49)

In an interview, the useful point is not the levels themselves but what each adds: level 1 gives addressability, level 2 lets caches, proxies and clients understand requests without reading your docs, and level 3 lets clients discover actions at runtime.

49. What is HATEOAS, and when is it useful? ​

The short answer

HATEOAS, hypermedia as the engine of application state, means a response tells the client what it can do next by including links, rather than the client building URLs from documentation. An order response might include a link to cancel it only while it can still be cancelled. It makes clients less coupled to URL structure and lets the server reveal allowed actions per state. It is rarely implemented fully, because most clients are written against documentation anyway, but links for paging and allowed actions are common and useful.

json
{
  "id": "ord_42",
  "status": "paid",
  "totalPence": 2499,
  "_links": {
    "self":   { "href": "/orders/ord_42" },
    "items":  { "href": "/orders/ord_42/items" },
    "cancel": { "href": "/orders/ord_42/cancellation", "method": "POST" },
    "invoice": { "href": "/orders/ord_42/invoice.pdf" }
  }
}

Once the order ships, the server simply leaves out the cancel link, and a client that shows buttons from links hides "Cancel" without needing its own copy of the rule.

Where it pays off: public APIs used by many independent clients, long-lived integrations where URLs may change, and paging, where next and prev links are standard (question 50).

Where it is usually skipped: internal APIs whose only client is your own front end, where the extra payload and design work bring little benefit.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Express & REST APIs
Express
REST API design
Testing
Other topics
Nothing picked yet