Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    HTTP and REST Essentials Cheat Sheet: Methods, Idempotency, Status Codes, Caching, Versioning

    Distinguish safe methods from idempotent operations.

    The HTTP rules a .NET API interview expects: which methods are safe and idempotent, which status code to return, how caching and conditional requests work, and how to version an API.

    At a glance

    • Safe means the client asks for no change of state (GET, HEAD, OPTIONS, TRACE). Idempotent means repeating the request has the same intended effect as sending it once: the safe methods, PUT and DELETE.
    • POST is neither. Retrying it needs a contract that prevents a duplicate effect, usually an idempotency key the server stores with the outcome.
    • Clients, proxies and retry policies act on the status class (2xx, 4xx, 5xx) before they read the body.
    • 401 means not authenticated; 403 means the request is understood and refused.
    • ETag with If-None-Match turns a repeat read into a 304; ETag with If-Match lets the server refuse a stale write, usually with 412.
    • Return errors as Problem Details (application/problem+json, RFC 9457, which replaced RFC 7807).

    Methods

    MethodSafeIdempotentTypical useTypical success
    GETYesYesRead a resource or a collection200, or 304 for a conditional read
    HEADYesYesGET without the body200
    OPTIONSYesYesCapabilities; the CORS preflight204 or 200
    POSTNoNoCreate a subordinate resource, or run a command201 with Location, 200, 202
    PUTNoYesReplace the resource at a known URI (or create it)200, 204, 201
    PATCHNoNot guaranteedPartial update: JSON Patch (RFC 6902) or JSON Merge Patch (RFC 7396)200, 204
    DELETENoYesRemove the resource204, 200, 202

    Status codes you must know

    CodeMeaningUse it when
    200OKSuccess with a body
    201CreatedA resource was created; Location points to it
    202AcceptedAccepted for later processing, not done yet; give a status URL
    204No ContentSuccess without a body
    301 / 308Moved permanently308 keeps the method and body; clients may turn a POST into a GET after 301
    302 / 307Moved temporarily307 keeps the method and body
    303See OtherAfter a POST, send the client to GET the result
    304Not ModifiedA conditional GET or HEAD found the representation unchanged
    400Bad RequestMalformed request or failed validation (what [ApiController] returns automatically)
    401UnauthorizedNo valid credentials; the response must carry WWW-Authenticate
    403ForbiddenUnderstood and refused, whoever the caller is
    404Not FoundNo such resource, or one you hide from this caller
    405Method Not AllowedThe method is not supported; send Allow
    409ConflictA state conflict: a duplicate, an invalid transition
    412Precondition FailedIf-Match or If-Unmodified-Since failed
    415Unsupported Media TypeThe request body's Content-Type is not accepted
    422Unprocessable ContentWell-formed but semantically invalid
    428Precondition RequiredYou require If-Match to prevent lost updates
    429Too Many RequestsRate limited; may send Retry-After
    500Internal Server ErrorAn unhandled server fault
    502Bad GatewayA gateway or proxy got an invalid response from upstream
    504Gateway TimeoutA gateway or proxy got no timely response from upstream
    503Service UnavailableOverloaded or in maintenance; may send Retry-After

    In ASP.NET Core, builder.Services.AddProblemDetails() registers the Problem Details service, and Results.Problem(...) or Results.ValidationProblem(...) return one from a minimal API.

    Retrying

    • Retry idempotent requests on transient answers: 408, 429, 502, 503, 504 and network failures.
    • Honour Retry-After, use bounded backoff with jitter, stop on cancellation, and keep a retry budget: Retry Budgets and Backpressure.
    • Do not retry most other 4xx answers unchanged: the same request fails the same way.

    Caching and conditional requests

    HeaderMeaning
    Cache-Control: max-age=60Fresh for 60 seconds
    Cache-Control: privateOnly the user's own cache may store it
    Cache-Control: publicShared caches may store it, even for an authenticated request
    Cache-Control: no-cacheMay be stored, but must be revalidated before each reuse
    Cache-Control: no-storeCaches must not store it
    s-maxageOverrides max-age for shared caches (CDNs, proxies)
    ETag / If-None-MatchA version tag; a match gives 304 for GET and HEAD, 412 for other methods
    Last-Modified / If-Modified-SinceA date-based validator, to the second
    If-MatchApply the write only if the current ETag matches, otherwise 412
    Vary: Accept-Encoding, AcceptThese request headers are part of the cache key
    • "abc" is a strong ETag (byte-for-byte the same); W/"abc" is weak (equivalent). If-Match uses the strong comparison, so a weak tag never matches it.
    • In ASP.NET Core, response caching middleware follows the HTTP cache headers; output caching (.NET 7 and later) is controlled by the server and can evict entries by tag.

    Conditional requests, run

    A plain C# model of an API that hands out ETags, answers repeat reads with 304 and requires If-Match on writes:

    C#Runs
    var store = new Dictionary<int, (string Body, int Version)>();
    int nextId = 1;
    
    (int Status, string? Header) Post(string body)
    {
        int id = nextId++;
        store[id] = (body, 1);
        return (201, $"Location: /items/{id}");
    }
    
    (int Status, string? Header) Get(int id, string? ifNoneMatch = null)
    {
        if (!store.TryGetValue(id, out var item)) return (404, null);
        string etag = $"\"v{item.Version}\"";
        return ifNoneMatch == etag ? (304, null) : (200, $"ETag: {etag}");
    }
    
    (int Status, string? Header) Put(int id, string body, string? ifMatch)
    {
        if (!store.TryGetValue(id, out var item)) return (404, null);
        if (ifMatch is null) return (428, null);                      // this API requires If-Match on writes
        if (ifMatch != $"\"v{item.Version}\"") return (412, null);   // changed since the client read it
        store[id] = (body, item.Version + 1);
        return (204, null);
    }
    
    void Show(string label, (int Status, string? Header) r) =>
        Console.WriteLine($"{label} -> {r.Status}{(r.Header is null ? "" : ", " + r.Header)}");
    
    Show("POST", Post("first"));
    Show("GET", Get(1));
    Show("GET If-None-Match \"v1\"", Get(1, "\"v1\""));
    Show("PUT without If-Match", Put(1, "second", null));
    Show("PUT If-Match \"v1\"", Put(1, "second", "\"v1\""));
    Show("same PUT retried, If-Match \"v1\"", Put(1, "second", "\"v1\""));
    Output
    POST -> 201, Location: /items/1
    GET -> 200, ETag: "v1"
    GET If-None-Match "v1" -> 304
    PUT without If-Match -> 428
    PUT If-Match "v1" -> 204
    same PUT retried, If-Match "v1" -> 412
    • In this model the retried PUT gets 412 although the first one succeeded: PUT is idempotent, but a request with a precondition can answer differently the second time. RFC 9110 also lets a server that knows the change already succeeded answer 2xx instead. After a lost response, read the resource again before deciding.
    • A real server parses lists of tags and *, and compares weakly for If-None-Match; this model compares one strong tag.

    REST design rules interviewers expect

    • Name resources with nouns, often plural and nested: /orders/42/lines. The method says the action, not the path (/getOrder).
    • Filter, sort and page in the query string: ?status=open&sort=-createdAt&limit=50&cursor=.... Prefer cursor (keyset) paging for large, changing sets: Stable Pagination in .NET APIs.
    • POST /orders answers 201 Created with Location: /orders/42.
    • Report errors with status codes and Problem Details, never 200 with "success": false.
    • Accept asks for a format; Content-Type describes the body that was sent.
    • Hand out an ETag on GET and require If-Match on PUT, PATCH and DELETE to stop lost updates.

    Versioning

    StrategyExampleForAgainst
    URL path/v1/ordersVisible, easy to route and cacheThe URI of the same resource changes
    Query string/orders?api-version=1.0Easy to defaultCaches must keep the query in the key
    Headerapi-version: 1.0Clean URIsLess visible; needs Vary
    Media typeAccept: application/json;v=1.0Versions the representation, not the URINeeds Vary: Accept and reader setup
    • In .NET, the Asp.Versioning.Http (minimal APIs) and Asp.Versioning.Mvc (controllers) packages read the version from the query string and the URL segment by default, and from a header or media type once those readers are configured. With ReportApiVersions on, they list supported and deprecated versions in response headers.
    • Version for breaking changes only. Adding an optional field is usually compatible, if clients ignore fields they do not know.

    Common mistakes

    • Returning 401 to a signed-in user who lacks permission: that is 403.
    • Retrying POST /payments with no stored idempotency key: a timeout and a retry can charge twice.
    • Using no-cache when you meant no-store for personal data.
    • Cache-Control: public on per-user responses behind a CDN.
    • Treating PUT as a partial update: it replaces the representation; partial changes are PATCH.
    • Ignoring ETags on PUT, so two editors overwrite each other.

    In an interview

    What is the difference between safe and idempotent? Safe methods ask for no change of state. Idempotent methods can be repeated with the same intended effect: every safe method is idempotent, and PUT and DELETE are idempotent without being safe.

    Is PATCH idempotent? Not by definition. A JSON Merge Patch that sets fields is idempotent in practice; a patch that appends to a list or increments a value is not.

    When do you return 401 and when 403? 401 when the caller is not authenticated (with a WWW-Authenticate header); 403 when the server understood the request and refuses it.

    400, 409, 412 or 422? 400 for a malformed or invalid request, 422 for a well-formed request that breaks the rules, 409 for a conflict with the current state, 412 when a precondition such as If-Match failed.

    How does a conditional GET produce a 304? The client sends the ETag it has in If-None-Match; if the server's current tag matches, it answers 304 with no body and the client reuses its copy.

    How do you stop a lost update between two editors? Return an ETag with the read and require If-Match on the write. The second editor's stale tag gets 412, so they reload and merge instead of overwriting.

    Which versioning strategy would you pick for a public API? URL path versioning is the most visible and the easiest to route and cache; header or media-type versioning keeps URIs stable but needs Vary and client discipline.

    Check yourself

    In the model above, a PUT with the current If-Match succeeds, but the response is lost. The client sends the same PUT with the same If-Match again, and nothing else changed in between. What does it get?

    A 204, because PUT is idempotent
    B 412, and that proves the first PUT failed
    C 412, although the first PUT succeeded
    D 428, because the tag is now missing
    Show answer

    Correct answer: C

    In the model the first PUT changed the version, so the old tag no longer matches; idempotency is about the effect, not about getting the same response.

    Option A: Idempotent methods do not promise identical responses to a repeat.

    Option B: The 412 only says the tag is stale; here it is stale because the first PUT succeeded.

    Option D: The request still carries If-Match, so the precondition is checked, not required.

    A signed-in user asks for an admin-only report they are not allowed to see. Which status fits?

    A 401 Unauthorized
    B 403 Forbidden
    C 404 Not Found, always
    D 400 Bad Request
    Show answer

    Correct answer: B

    The caller is known and the request is understood, but it is refused: that is 403 (or 404 if the API chooses to hide the resource).

    Option A: 401 is for a caller without valid credentials.

    Option C: 404 is an option for hiding a resource, not the required answer.

    Option D: Nothing is wrong with the request itself.

    Which Cache-Control value forbids caches from storing a response?

    A no-cache
    B private
    C no-store
    D max-age=0
    Show answer

    Correct answer: C

    no-store tells caches not to store the response at all.

    Option A: no-cache allows storing, with revalidation before each reuse.

    Option B: private still lets the user's own cache store it.

    Option D: max-age=0 makes the response stale at once, but it may still be stored and revalidated.

    Sources

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·