Appearance
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.
| Constraint | Meaning | What it gives you |
|---|---|---|
| Client-server | UI and data storage are separate | Each side changes independently |
| Stateless | Each request carries everything needed; no session state on the server between requests | Any server can handle any request: easy scaling |
| Cacheable | Responses say whether and how long they can be cached | Less load, faster clients |
| Uniform interface | Resources by URL, standard methods, self-describing messages, links | One way to use every resource |
| Layered system | Clients cannot tell whether they talk to the server or a proxy | Load balancers, caches and gateways in between |
| Code on demand, optional | Servers may send code, such as JavaScript | Rarely 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-collectionREST 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.
| CRUD | HTTP | URL | Success status |
|---|---|---|---|
| Create | POST | /products | 201 Created |
| Read many | GET | /products?category=tea | 200 OK |
| Read one | GET | /products/tea-earl-grey | 200 OK |
| Update all | PUT | /products/tea-earl-grey | 200 OK |
| Update part | PATCH | /products/tea-earl-grey | 200 OK |
| Delete | DELETE | /products/tea-earl-grey | 204 No Content |
Actions that do not fit CRUD:
| Action | Common REST shape |
|---|---|
| Cancel an order | POST /orders/ord_42/cancellation, or PATCH /orders/ord_42 with { "status": "cancelled" } |
| Send a password reset email | POST /password-resets |
| Retry a failed payment | POST /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.
| Code | Meaning | Example |
|---|---|---|
200 OK | Success, with a body | GET /orders/ord_42 |
201 Created | A resource was created | POST /orders, plus Location: /orders/ord_42 |
202 Accepted | Accepted, will be done later | Export queued |
204 No Content | Success, no body | DELETE /cart/items/tea |
304 Not Modified | Cached copy is still valid | Conditional GET (question 55) |
400 Bad Request | Malformed or invalid input | Missing required field |
401 Unauthorized | Not authenticated: who are you? | Missing or expired token |
403 Forbidden | Authenticated, not allowed | A customer calling an admin endpoint |
404 Not Found | No such resource, or hidden from you | Unknown order ID |
405 Method Not Allowed | Wrong method for this URL | DELETE /orders |
409 Conflict | Clashes with current state | Email already registered, stale version |
412 Precondition Failed | If-Match did not match | Optimistic concurrency (question 56) |
413 Content Too Large | Body too large | 50 MB upload to a 5 MB endpoint |
415 Unsupported Media Type | Wrong Content-Type | XML sent to a JSON API |
422 Unprocessable Content | Syntax fine, meaning invalid | Delivery date in the past |
429 Too Many Requests | Rate limited, with Retry-After | Too many login attempts |
500 Internal Server Error | Unexpected failure | A bug |
502 Bad Gateway | An upstream service sent a bad response | Payment provider returned garbage |
503 Service Unavailable | Temporarily down or overloaded | Maintenance, with Retry-After |
504 Gateway Timeout | An upstream service did not answer in time | Inventory 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.
| Method | Safe, no changes | Idempotent | Retry blindly? |
|---|---|---|---|
GET, HEAD, OPTIONS | Yes | Yes | Yes |
PUT | No | Yes | Yes |
DELETE | No | Yes | Yes |
PATCH | No | Depends | Only if the change is a "set" |
POST | No | No | Only 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 timeIdempotency 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.
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)
})- Scope keys per user, so one user's key can never return another user's result.
- Same key, different body is a client bug; refuse it rather than guess.
- The first request is still running: tell the client to wait and retry.
- Already done: return the stored result, byte for byte.
- Reserve the key first, protected by a unique database constraint, so two retries arriving at the same moment cannot both pass the check.
- 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.
| Good | Avoid | Why |
|---|---|---|
GET /orders | GET /getAllOrders | The method is the verb |
GET /orders/ord_42 | GET /order?id=42 | Path for identity, query for options |
POST /orders | POST /orders/create | POST to a collection already means create |
/gift-cards | /giftCards, /Gift_Cards | Consistent, readable, case-safe |
/customers/c17/orders | /customers/c17/orders/ord_42/items/3/notes/9 | Deep nesting becomes rigid |
/orders?status=paid&sort=-createdAt | /orders/paid/sorted-by-date | Filters 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.
| Level | Name | Example |
|---|---|---|
| 0 | One endpoint, RPC style | POST /api with { "action": "getOrder", "id": 42 } |
| 1 | Resources | POST /orders/42 with { "action": "get" } |
| 2 | HTTP methods and status codes | GET /orders/42 → 200, or 404 |
| 3 | Hypermedia controls | Responses 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.