📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is REST? Explain Fielding's architectural constraints (client-server, statelessness, cacheability, uniform interface, layered system, code on demand), what the uniform interface really requires, and what people mean in practice when they call an API "RESTful".

REST as an architectural style: Fielding's six constraints, the four parts of the uniform interface, and the gap between academic REST and the pragmatic "RESTful" JSON-over-HTTP APIs most teams build.

Junior Theory Beginner api-design aspnet-core http rest rest-constraints web-api

🎯 Key points

  • REST = Roy Fielding's 2000 dissertation: an architectural style, not a protocol or standard
  • Six constraints: client-server, stateless, cacheable, uniform interface, layered system, plus code on demand (the one constraint Fielding defined as optional)
  • Uniform interface: resource identification (URIs), manipulation through representations, self-descriptive messages, HATEOAS
  • HATEOAS: responses carry links/forms for the next valid actions, so clients follow links instead of hard-coding URLs and workflows
  • Stateless: each request carries everything needed (e.g. bearer token); no server session affinity
  • Cacheable: responses label themselves with Cache-Control/ETag so intermediaries can reuse them
  • Layered: client cannot tell if it talks to a CDN, gateway (APIM, YARP) or the origin
  • Pragmatic "RESTful" = resources + HTTP method semantics + status codes + JSON, usually without HATEOAS (Richardson level 2)

⏱ 30-second answer

REST (Representational State Transfer) is an architectural style Roy Fielding described in 2000, not a protocol. It is defined by six constraints: client-server, stateless requests, cacheable responses, a uniform interface, a layered system, and optional code on demand. The uniform interface is the heart of it: resources identified by URIs, changed through representations (JSON, XML), self-descriptive messages (methods, status codes, media types) and hypermedia links that drive the client (HATEOAS).

In practice, when a team says "RESTful" they usually mean resource-oriented URLs, correct HTTP methods and status codes, and JSON, but no hypermedia. That is fine for most internal and partner APIs; the trade-off is that clients hard-code URLs and workflows instead of discovering them.

🗣 Full answer (senior)

How I would answer this in an interview

"REST is an architectural style from Roy Fielding's 2000 dissertation, describing what made the web itself scale. It isn't a standard or a library; it's a set of constraints, and you get certain properties if you follow them. Client-server separates the UI from storage. Stateless means every request carries everything the server needs, such as the bearer token, so any instance can serve it and you can scale horizontally. Cacheable means responses say whether and for how long they can be reused. Layered system means the client can't tell whether it's talking to a CDN, an API gateway or the origin. Code on demand, the server sending executable code such as JavaScript, is the one constraint Fielding made optional. And the uniform interface is the big one: resources have identifiers, you manipulate them by sending representations, messages are self-descriptive through methods, status codes and media types, and hypermedia links tell the client what it can do next.

In ASP.NET Core most of that shows up as resource routes like /orders/{id}, MapGet, MapPut and MapDelete used for their real meanings, TypedResults.Created with a Location header, ProblemDetails for errors and Cache-Control or ETag headers where reads are cacheable. Statelessness means no in-memory session; if I need state across requests it goes into the resource or a shared store.

The mistake I see is calling any JSON-over-HTTP API RESTful, including RPC endpoints like /api/createOrder that use POST for everything. What most of us build is Richardson level 2: resources plus HTTP semantics, without hypermedia. I'm comfortable saying that honestly; the senior point is knowing which constraints you've kept, which you've dropped, and what that costs your clients."


The six constraints and what they buy you

Constraint Means Property you get ASP.NET Core / Azure shape
Client-server UI and data storage evolve separately Independent deployment SPA or mobile app + API
Stateless No server-side session between requests Horizontal scale, simple failover JWT bearer tokens, no sticky sessions
Cacheable Responses declare cacheability Lower latency and load Cache-Control, ETag, output caching, Azure Front Door
Uniform interface Standard way to identify and change resources Generic tooling and intermediaries URIs, methods, status codes, media types, links
Layered system Client sees one layer only Gateways, CDNs, proxies can be inserted Azure API Management, YARP
Code on demand (optional) Server can send executable code Extensibility Browsers running server-sent JavaScript; rare for JSON APIs

The four parts of the uniform interface

Part Example
Identification of resources /customers/42/orders/1001
Manipulation through representations PUT a JSON body that replaces the order
Self-descriptive messages Content-Type: application/json, 201 Created, Cache-Control: max-age=60
Hypermedia as the engine of application state "links": { "cancel": { "href": "/orders/1001/cancellation" } }

HATEOAS in one paragraph

Hypermedia as the engine of application state means the client starts at one entry URL and from then on only follows links and forms the server puts in each response, exactly as a browser follows links in HTML. If an order is already shipped, the server simply omits the cancel link, so the client doesn't need to duplicate the business rule "only unshipped orders can be cancelled", and the server can move resources to new URLs without breaking clients. The cost is a richer media type (HAL, JSON:API, Siren), clients written to follow links rather than build URLs, and more design effort, which is why most JSON APIs skip it and rely on OpenAPI documentation instead.

"RESTful" in practice

Academic REST Typical "RESTful" API
Hypermedia drives every transition URLs documented in OpenAPI and hard-coded in clients
Media types define semantics application/json plus a schema
Clients discover capabilities Clients read docs and SDKs

Production example

A [team] moved session state from in-memory ISession to the request (JWT claims plus resource state in Azure SQL). That removed sticky sessions on the load balancer, and scaling from [2 to 6] instances during a sale cut p95 latency from [~900 ms to ~250 ms] without users being logged out during deployments.

🔍 What the interviewer is checking

Checks that the candidate knows REST is an architectural style with specific constraints and can separate textbook REST from what teams actually ship.

Green flags

  • Names Fielding and most of the six constraints
  • Explains statelessness as no server-side session, not "no database"
  • Describes the uniform interface, including hypermedia
  • Honestly calls most APIs Richardson level 2 and explains the trade-off

Red flags

  • "REST means JSON over HTTP"
  • Thinks REST is a protocol or a .NET library
  • Uses in-memory session and still calls it stateless

📚 Learn in depth

1. Where REST comes from

Fielding co-authored HTTP/1.1 and described REST in chapter 5 of his 2000 dissertation as the style that explained why the web scaled. He derived it by starting from "no constraints" and adding one at a time, each giving a property (scalability, visibility, evolvability) at some cost (usually efficiency).

2. Statelessness is about session state

Client                     Instance A     Instance B
  | GET /orders (token) --> | serves      |
  | GET /orders/7 (token) ---------------> | serves (no shared session needed)

Resource state (an order in SQL) lives on the server; that's fine. What REST forbids is application/session state kept between requests on the server. Each request must be understandable on its own. Cost: requests are bigger (a token every time), but any instance can answer and a failed instance loses nothing.

3. Cacheability needs the server's cooperation

Intermediaries can only cache what the response labels. Cache-Control: public, max-age=300 lets Azure Front Door serve 5 minutes of reads; ETag lets clients revalidate cheaply with If-None-Match and get 304 Not Modified.

4. The layered system

Client -> Azure Front Door -> API Management -> YARP -> ASP.NET Core

Each layer only knows its neighbours. This is why X-Forwarded-* headers exist: the origin needs to reconstruct what the client actually sent.

5. The uniform interface and its trade-off

Using the same methods and status codes for every resource means a generic gateway can retry PUTs, a CDN can cache GETs and a browser can follow links. The cost Fielding names is efficiency: data is transferred in a standard form rather than one optimised for each application. That is one reason gRPC exists for internal, chatty calls.

6. Is hypermedia required?

Fielding has said (2008, "REST APIs must be hypertext-driven") that without hypermedia an API is not REST. The Richardson maturity model puts that as level 3. Most production APIs stop at level 2 and use OpenAPI for discoverability instead.

Try it yourself

  1. Build a Minimal API with MapGet("/orders/{id}") and MapPut, then call it through curl -i and list which parts of the response are "self-descriptive".
  2. Add ISession to an API, run two instances behind YARP without sticky sessions, and watch requests lose state.
  3. Add Cache-Control: public, max-age=60 to a GET and observe a browser or proxy serving it without hitting the server (check the server log).
  4. Classify three APIs you use (e.g. GitHub, Stripe, Microsoft Graph) against the six constraints.

💻 Code

A small Minimal API that respects the main constraints: resource URIs, method semantics, self-descriptive responses, cacheability and no server session.

// Program.cs (.NET 10)
using System.Collections.Concurrent;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();          // self-descriptive errors (RFC 9457)
var app = builder.Build();

var orders = new ConcurrentDictionary<int, Order>();
var nextId = 0;

// Resource identification: /orders/{id}. Stateless: nothing kept between calls except resource state.
app.MapGet("/orders/{id:int}", (int id, HttpContext ctx) =>
{
    if (!orders.TryGetValue(id, out var order))
        return Results.Problem(statusCode: 404, title: "Order not found");

    // Cacheable: label the response so clients and proxies may reuse it.
    ctx.Response.Headers.CacheControl = "private, max-age=30";
    return Results.Ok(order);
});

// Manipulation through representations: the client sends a representation, the server creates a resource.
app.MapPost("/orders", (CreateOrder cmd) =>
{
    var id = Interlocked.Increment(ref nextId);
    var order = new Order(id, cmd.CustomerId, cmd.Total);
    orders[id] = order;
    return Results.Created($"/orders/{id}", order); // 201 + Location
});

app.Run();

public sealed record Order(int Id, int CustomerId, decimal Total);
public sealed record CreateOrder(int CustomerId, decimal Total);

⚠ Common mistakes

  • Mistake: Calling REST a protocol or a standard. Why it is wrong: It is an architectural style; HTTP is the protocol it is usually applied to. Instead: Say "REST is a set of constraints; HTTP is how we usually implement them".
  • Mistake: Keeping per-user state in server memory (ISession, static dictionaries). Why it is wrong: It breaks statelessness, forces sticky sessions and loses state on restarts or scale-in. Instead: Put session data in the token, the resource, or a shared store such as Redis.
  • Mistake: Calling RPC-style endpoints (POST /api/createOrder) RESTful. Why it is wrong: There are no resources and no method semantics, so caches and retries can't help. Instead: Model resources (POST /orders) and use methods for their meaning.
  • Mistake: Shipping GET endpoints with no cache headers at all, or with no-store copied everywhere. Why it is wrong: Without explicit Cache-Control or ETag, every read hits the database, conditional requests (304) are impossible and intermediaries may apply heuristic caching you didn't intend; blanket no-store throws away the cacheability constraint entirely. Instead: Decide cacheability per endpoint (private, max-age=30, public for shared reference data, no-store only for sensitive data) and add ETags for revalidation.
  • Mistake: Claiming full REST while dropping hypermedia. Why it is wrong: Interviewers who know Fielding will call it out. Instead: Say it is Richardson level 2 and explain why that's a deliberate choice.
  • Mistake: Forgetting code on demand exists, or claiming it is mandatory. Why it is wrong: It is part of Fielding's definition but explicitly optional; the web uses it (JavaScript), JSON APIs almost never do. Instead: Name it, say it's optional, and give the browser-script example.
  • Mistake: Treating REST as mandatory for every API. Why it is wrong: Chatty internal calls or streaming may fit gRPC or messaging better. Instead: Choose the style per use case.

🏛 Senior insight: trade-offs

Seniors treat REST as a menu of constraints with known payoffs, not a purity test. Statelessness and cacheability are the ones that pay for themselves operationally: they let you scale out on Azure App Service or Container Apps without session affinity and let Azure Front Door or output caching absorb read load. Hypermedia pays off mainly for long-lived public APIs with many independent clients, and even then OpenAPI plus good versioning usually wins on cost.

What I measure: cache hit ratio at the CDN, the share of requests that need affinity (should be zero), and how often clients break when we change URLs (a signal that hypermedia or better versioning would help).

Constraint Keep it when Cost Consider dropping when
Stateless Almost always Larger requests (tokens) Real-time connections (SignalR)
Cacheable Read-heavy resources Invalidation complexity Highly personalised, rapidly changing data
Uniform interface (methods, status codes) Any HTTP API Some inefficiency vs custom RPC Internal high-throughput calls (gRPC)
Hypermedia Public APIs with many clients and evolving workflows Design and client complexity Internal APIs with a known SPA or mobile client

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions methods, status codes or caching headers Why: Checks the underlying HTTP knowledge REST relies on
    How to answer

    HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.

    • Methods: GET/HEAD/OPTIONS are safe; GET, PUT, DELETE are idempotent (repeating has the same effect); POST and usually PATCH are not, so retries need an idempotency key.
    • Status codes: 2xx success, 3xx redirect/not modified, 4xx client error (400, 401 vs 403, 404, 409, 422, 429), 5xx server error (500, and 502/503/504 usually from proxies or gateways).
    • Headers: Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.
    • Versions: HTTP/1.1 is text with one request at a time per connection; HTTP/2 is binary with multiplexed streams and header compression on one TCP connection; HTTP/3 does the same over QUIC/UDP, removing TCP head-of-line blocking.
  2. When: Candidate mentions the uniform interface or method semantics Why: Checks whether they know which methods are safe and idempotent
    How to answer

    GET reads, POST creates or runs a command, PUT replaces a resource at a known URI, PATCH partially updates it, DELETE removes it, HEAD is GET without the body, and OPTIONS asks what is allowed (used by CORS preflight).

    • Safe (no intended state change): GET, HEAD, OPTIONS.
    • Idempotent (repeating has the same effect as doing it once): the safe methods plus PUT and DELETE.
    • POST and PATCH are neither, unless you make them so.

    These properties are a contract that caches, proxies, browsers and retry policies rely on: a gateway may retry a timed-out PUT but must not blindly retry a POST. Breaking the contract, such as changing state on GET, causes duplicate side effects and crawler disasters.

↩ Usually asked after

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me