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.
ETagwithIf-None-Matchturns a repeat read into a 304;ETagwithIf-Matchlets the server refuse a stale write, usually with 412.- Return errors as Problem Details (
application/problem+json, RFC 9457, which replaced RFC 7807).
Methods
| Method | Safe | Idempotent | Typical use | Typical success |
|---|---|---|---|---|
| GET | Yes | Yes | Read a resource or a collection | 200, or 304 for a conditional read |
| HEAD | Yes | Yes | GET without the body | 200 |
| OPTIONS | Yes | Yes | Capabilities; the CORS preflight | 204 or 200 |
| POST | No | No | Create a subordinate resource, or run a command | 201 with Location, 200, 202 |
| PUT | No | Yes | Replace the resource at a known URI (or create it) | 200, 204, 201 |
| PATCH | No | Not guaranteed | Partial update: JSON Patch (RFC 6902) or JSON Merge Patch (RFC 7396) | 200, 204 |
| DELETE | No | Yes | Remove the resource | 204, 200, 202 |
- Idempotent is about the effect, not the response: a second DELETE may answer 404, and that is fine.
- A retried POST needs a server-side contract: see Idempotency Keys for Reliable HTTP APIs.
Status codes you must know
| Code | Meaning | Use it when |
|---|---|---|
| 200 | OK | Success with a body |
| 201 | Created | A resource was created; Location points to it |
| 202 | Accepted | Accepted for later processing, not done yet; give a status URL |
| 204 | No Content | Success without a body |
| 301 / 308 | Moved permanently | 308 keeps the method and body; clients may turn a POST into a GET after 301 |
| 302 / 307 | Moved temporarily | 307 keeps the method and body |
| 303 | See Other | After a POST, send the client to GET the result |
| 304 | Not Modified | A conditional GET or HEAD found the representation unchanged |
| 400 | Bad Request | Malformed request or failed validation (what [ApiController] returns automatically) |
| 401 | Unauthorized | No valid credentials; the response must carry WWW-Authenticate |
| 403 | Forbidden | Understood and refused, whoever the caller is |
| 404 | Not Found | No such resource, or one you hide from this caller |
| 405 | Method Not Allowed | The method is not supported; send Allow |
| 409 | Conflict | A state conflict: a duplicate, an invalid transition |
| 412 | Precondition Failed | If-Match or If-Unmodified-Since failed |
| 415 | Unsupported Media Type | The request body's Content-Type is not accepted |
| 422 | Unprocessable Content | Well-formed but semantically invalid |
| 428 | Precondition Required | You require If-Match to prevent lost updates |
| 429 | Too Many Requests | Rate limited; may send Retry-After |
| 500 | Internal Server Error | An unhandled server fault |
| 502 | Bad Gateway | A gateway or proxy got an invalid response from upstream |
| 504 | Gateway Timeout | A gateway or proxy got no timely response from upstream |
| 503 | Service Unavailable | Overloaded 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
| Header | Meaning |
|---|---|
Cache-Control: max-age=60 | Fresh for 60 seconds |
Cache-Control: private | Only the user's own cache may store it |
Cache-Control: public | Shared caches may store it, even for an authenticated request |
Cache-Control: no-cache | May be stored, but must be revalidated before each reuse |
Cache-Control: no-store | Caches must not store it |
s-maxage | Overrides max-age for shared caches (CDNs, proxies) |
ETag / If-None-Match | A version tag; a match gives 304 for GET and HEAD, 412 for other methods |
Last-Modified / If-Modified-Since | A date-based validator, to the second |
If-Match | Apply the write only if the current ETag matches, otherwise 412 |
Vary: Accept-Encoding, Accept | These request headers are part of the cache key |
"abc"is a strong ETag (byte-for-byte the same);W/"abc"is weak (equivalent).If-Matchuses 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:
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\""));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 forIf-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 /ordersanswers201 CreatedwithLocation: /orders/42.- Report errors with status codes and Problem Details, never
200with"success": false. Acceptasks for a format;Content-Typedescribes the body that was sent.- Hand out an
ETagon GET and requireIf-Matchon PUT, PATCH and DELETE to stop lost updates.
Versioning
| Strategy | Example | For | Against |
|---|---|---|---|
| URL path | /v1/orders | Visible, easy to route and cache | The URI of the same resource changes |
| Query string | /orders?api-version=1.0 | Easy to default | Caches must keep the query in the key |
| Header | api-version: 1.0 | Clean URIs | Less visible; needs Vary |
| Media type | Accept: application/json;v=1.0 | Versions the representation, not the URI | Needs Vary: Accept and reader setup |
- In .NET, the
Asp.Versioning.Http(minimal APIs) andAsp.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. WithReportApiVersionson, 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 /paymentswith no stored idempotency key: a timeout and a retry can charge twice. - Using
no-cachewhen you meantno-storefor personal data. Cache-Control: publicon 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?
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?
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?
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.
Related on TechInterviewNotes
- ASP.NET Core Validation and Problem Details Companion: validation errors returned as Problem Details.
- .NET Networking Interview Checklist, and HTTP/1.1 vs HTTP/2 vs HTTP/3 in .NET from Networking for .NET Developers.
- Idempotency Keys for Reliable HTTP APIs: retries that do not repeat a write.
Sources
- RFC 9110: HTTP Semantics: methods (section 9), conditional requests (section 13), status codes (section 15).
- RFC 9111: HTTP Caching:
Cache-Controland freshness. - RFC 9457: Problem Details for HTTP APIs: the error body.
- Handle errors in ASP.NET Core APIs:
AddProblemDetailsand the Problem Details service. - Create web APIs with ASP.NET Core: automatic 400 responses with
[ApiController]. - Output caching middleware: server-controlled caching with tags.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·