1. Foundational Concepts & Core Architecture
What does REST stand for, and who defined it?
Answer: Representational State Transfer, defined by Roy Fielding in his 2000 doctoral dissertation (Architectural Styles and the Design of Network-based Software Architectures). It is an architectural style for distributed hypermedia systems.
Key Takeaway: REST isn’t a protocol or a standard; it’s a set of architectural constraints designed to maximize scalability, modifiability, and distributed performance.
What are the 6 core constraints of the REST architectural style?
Answer:
- Client-Server: Separation of concerns between the user interface (client) and data storage/processing (server).
- Stateless: Each request from client to server must contain all necessary context.
- Cacheability: Responses must define themselves as cacheable or non-cacheable to prevent unnecessary network roundtrips.
- Layered System: A client cannot tell whether it is connected directly to the end server or an intermediary (e.g., load balancer, proxy, CDN).
- Uniform Interface: Simplifies and decouples the architecture. Relies on resource identification, manipulation through representations, self-descriptive messages, and HATEOAS.
- Code-on-Demand (Optional): Servers can temporarily extend or customize client functionality by transferring executable code (e.g., JavaScript applets).
What does "Stateless" mean in the context of REST?
Answer: Every request from a client must contain all the necessary context and authentication credentials needed to process it. The server cannot rely on stored session state from previous requests.
Benefits: Improves scalability (any server instance can handle any request without session affinity/sticky sessions) and reliability.
What are the constraints of a "Uniform Interface"?
Answer:
- Identification of Resources: URIs identify individual resources.
- Manipulation through Representations: Clients receive representations of resources and manipulate them via standard methods.
- Self-Descriptive Messages: Each message includes enough info to process it (e.g., correct media types, content-type headers).
- HATEOAS: Hypermedia acts as the engine of application state.
2. URI Design & Resource Modeling
How should URIs be structured in a REST API?
Answer: URIs should represent resources (nouns, not verbs) and should generally be pluralized.
- Good:
GET /users,POST /orders- Bad:
GET /getUsers,POST /createOrder
How do you handle nested resources in URI paths?
Answer: Reflect ownership or hierarchy cleanly using path parameters.
- Example:
GET /users/{userId}/ordersretrieves all orders belonging to a specific user.- Warning: Avoid nesting deeper than 2 or 3 levels (e.g., use query parameters instead of
/users/{userId}/orders/{orderId}/items/{itemId}).
How should filtering, sorting, and pagination be handled?
Answer: Use query parameters rather than modifying path segments.
- Filtering:
GET /products?category=electronics&status=active- Sorting:
GET /products?sort=-price,name(orsort=price:desc)- Pagination:
GET /products?limit=20&offset=40or cursor-based pagination (GET /products?cursor=eyJpZCI6MTB9).
How do you handle RPC-style "actions" or "do something" operations that don't map cleanly to CRUD?
Answer: Model the action as a sub-resource or use a verb suffix if unavoidable, though standard REST prefers creating a resource.
- Examples:
POST /orders/{id}/cancelorPOST /subscriptions/{id}/activate.
3. HTTP Methods & Semantics
Explain the difference between Safe and Idempotent methods.
Answer:
- Safe: Methods that do not alter the server state (e.g.,
GET,HEAD,OPTIONS). Running them multiple times has no side effects on server data.- Idempotent: Methods that can be called multiple times with the same effect as calling them once. Includes all safe methods, plus
PUTandDELETE.POSTis not idempotent.
What is the exact difference between
PUTandPOST?Answer:
POSTis used to create a resource where the server determines the URI. It is non-idempotent (sending it twice creates two separate resources).PUTis used to replace or create a resource at a client-specified URI, and it is idempotent.
What is the difference between
PUTandPATCH?Answer:
PUTreplaces the entire resource. Missing fields in the payload may be cleared or defaulted.PATCHperforms a partial update, modifying only the attributes explicitly provided in the request body.
When would you use
HEADandOPTIONS?Answer:
HEADis identical toGETbut returns only HTTP headers without the response body (useful for checking resource metadata, file size, or existence before downloading).OPTIONSdescribes communication options for the target resource, heavily used for CORS (Cross-Origin Resource Sharing) preflight checks.
4. Status Codes & Payload Design
What are the common HTTP status code classes, and which codes are standard for REST success/failure?
Answer:
200 OK: Standard success forGET,PUT,PATCH.201 Created: Success forPOSTthat creates a resource (usually paired with aLocationheader).204 No Content: Success with no body returned, typically used forDELETEor successful updates.400 Bad Request: Validation failure or malformed JSON syntax.401 Unauthorized: Missing or invalid authentication credentials.403 Forbidden: Authenticated, but lacking permissions to access the resource.404 Not Found: Resource does not exist.409 Conflict: Request conflict, such as a duplicate unique constraint violation (e.g., email already registered).422 Unprocessable Entity: Syntactically correct request, but semantic validation errors occurred.500 Internal Server Error: Unhandled server-side failure.
How should error payloads be structured?
Answer: Use a consistent, machine-readable format such as RFC 7807 (Problem Details for HTTP APIs), containing standard fields like
type,title,status,detail, andinstance.
5. Advanced REST & Architectural Depth
What is the Richardson Maturity Model?
Answer: A model that breaks down REST maturity into 4 levels:
- Level 0: The Swamp of POX (Plain Old XML/JSON) — Single URI, single HTTP method (
POSTfor everything).- Level 1: Resources — Multiple URIs, but still ignoring HTTP verbs (e.g.,
POST /getUsers,POST /deleteUser).- Level 2: HTTP Verbs — Proper use of URIs and standard HTTP methods (
GET,POST,PUT,DELETE).- Level 3: HATEOAS — Hypermedia controls included in responses to guide the client on available next actions.
What is HATEOAS, and why is it rarely implemented strictly in practice?
Answer: HATEOAS stands for Hypermedia as the Engine of Application State. It means responses include links to related actions. It’s rare because it adds payload bloat, tight coupling to link generation patterns, and increases client-side parsing complexity when simple documentation/SDKs suffice.
How do you handle API Versioning?
Answer: Common strategies include:
- URI Path Versioning:
/api/v1/users(Most popular, highly visible, easy to route).- Header Versioning:
Accept: application/vnd.mycompany.v1+json(Cleaner URIs, harder to test directly in a browser).- Query Parameter Versioning:
/users?version=1(Rare, generally discouraged).
How do you handle long-running operations asynchronously?
Answer: Return a
202 Acceptedstatus code along with aLocationheader pointing to a status-tracking endpoint where the client can poll for progress (e.g.,GET /tasks/{taskId}).
6. Security, Performance & Scalability
How does statelessness impact API security and authentication?
Answer: Since sessions aren’t stored on the server, authentication tokens (such as JSON Web Tokens - JWTs or opaque OAuth2 bearer tokens) must be passed in the
Authorizationheader on every request.
How do you design a REST API to be cacheable?
Answer: By leveraging HTTP caching headers like
Cache-Control,ETag(Entity Tags), andIf-None-Match. If a client requests a resource with a matchingETag, the server responds with a304 Not Modifiedwithout re-transferring the full payload.
What strategies are used to prevent API abuse?
Answer: Rate limiting (returning
429 Too Many Requests), throttling, payload size limits, and pagination quotas.