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

📚 Interview question

Which HTTP method would you use for each operation in an API? Explain GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD, which are safe and which are idempotent, which may carry a body, and why those properties matter in practice.

The HTTP methods as an API contract: meaning of each, the safe, idempotent and cacheable properties, body rules, and how retries, caches and proxies rely on them.

Junior Theory Beginner aspnet-core http http-methods idempotency rest web-api

🎯 Key points

  • Safe = no intended state change: GET, HEAD, OPTIONS (and TRACE)
  • Idempotent = same effect if repeated: all safe methods plus PUT and DELETE
  • POST is not idempotent; PATCH is not guaranteed idempotent but can be designed to be (e.g. merge patch setting fixed values)
  • Idempotency is about server state, not the response (second DELETE may return 404)
  • Bodies: POST, PUT, PATCH carry them; GET body has no defined semantics
  • GET and HEAD responses are cacheable by default; POST only with explicit freshness
  • Retrying a non-idempotent call after a timeout can create duplicates (orders, payments); resilience handlers should skip unsafe methods
  • ASP.NET Core: MapGet/MapPost/MapPut/MapPatch/MapDelete, [HttpGet] etc.

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I think of the methods as a contract between my API and everything in between: browsers, CDNs, gateways and retry policies. GET reads a representation. POST submits something for the server to process, usually creating a resource in a collection or running a command. PUT replaces the resource at the URI I name, and can create it if the client owns the id. PATCH applies a partial change. DELETE removes the resource. HEAD is GET without the body, handy for existence or size checks. OPTIONS asks which methods and headers are allowed, and browsers send it as the CORS preflight.

Two properties matter. A safe method has no intended side effects: GET, HEAD and OPTIONS. An idempotent method has the same effect on the server whether you send it once or five times: the safe methods plus PUT and DELETE. POST and PATCH are neither by definition. Idempotency is about state, not the response: the first DELETE returns 204 and the second may return 404, but the order is gone either way. In ASP.NET Core I express this with MapGet, MapPut, MapDelete and so on, and resilience handlers on HttpClient can then decide what's safe to retry.

The mistake I see is treating methods as interchangeable labels: a GET that sends an email, or POST used for everything. That breaks caches, makes link prefetchers trigger actions and means a timeout can't be retried safely. If an operation must be retryable but isn't naturally idempotent, like taking a payment, I make it idempotent with an idempotency key rather than pretending POST is safe."


Method properties (RFC 9110)

Method Meaning Safe Idempotent Request body Cacheable
GET Read representation Yes Yes No defined semantics Yes
HEAD GET without body Yes Yes No defined semantics Yes
OPTIONS Allowed methods / CORS preflight Yes Yes Rarely No
POST Process / create in collection No No Yes Only with explicit freshness info
PUT Replace at this URI No Yes Yes No
PATCH Partial update No No (can be designed to be) Yes No
DELETE Remove No Yes No defined semantics No

Typical mapping

Operation Method and URI Success
List orders GET /orders 200
Get one GET /orders/42 200 / 404
Create (server id) POST /orders 201 + Location
Create or replace (client id) PUT /orders/{guid} 201 or 200/204
Partial update PATCH /orders/42 200 / 204
Delete DELETE /orders/42 204

Production example

A [reporting] API exposed GET /reports/{id}/regenerate. A browser extension that prefetched links triggered [hundreds of] regenerations a day, each costing ~40 s of SQL CPU. Changing it to POST /reports/{id}/regenerations (202 Accepted) stopped the accidental load overnight.

🔍 What the interviewer is checking

Checks that the candidate knows method semantics precisely and understands why caches, proxies and retry policies depend on them.

Green flags

  • Correctly lists safe (GET, HEAD, OPTIONS) and idempotent (+ PUT, DELETE) methods
  • Explains idempotency as effect on state, not identical responses
  • Connects idempotency to retries and duplicates
  • Knows PUT is replace and PATCH is partial
  • Mentions OPTIONS for CORS preflight

Red flags

  • Says POST is idempotent or PATCH is always idempotent
  • Happy to change state on GET
  • Uses POST for everything "because it always works"

📚 Learn in depth

1. Where the definitions come from

RFC 9110 (HTTP Semantics, 2022) defines GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS and TRACE. PATCH is defined separately in RFC 5789. The safe and idempotent properties are promises the server makes; intermediaries are allowed to act on them.

2. Safe does not mean "no side effects at all"

A GET may write an access log or increment a view counter. Safe means the client did not request a state change and is not responsible for it. If GET triggers business effects (sending email, deleting data), crawlers, prefetchers, link previews in chat apps and security scanners will trigger them too.

3. Idempotency is about the resulting state

PUT /orders/42 {status: Shipped}   x3   -> state: Shipped (same as once)
DELETE /orders/42                  x3   -> state: gone   (204, then 404, 404)
POST /orders {...}                 x3   -> state: three orders (not idempotent)
PATCH /orders/42 [{op: add, path: /lines/-, ...}] x3 -> three lines added

PATCH with JSON Merge Patch that sets fields to fixed values happens to be idempotent; PATCH with a JSON Patch add to an array is not. That is why the RFC does not promise it.

4. Why intermediaries care

Client --> API gateway --> Service
           |  timeout after 30 s
           |  Is it safe to retry?
           |    GET/PUT/DELETE: yes, the effect is the same
           |    POST/PATCH:     unknown, it may have run already

The .NET resilience pipeline (Microsoft.Extensions.Http.Resilience, AddStandardResilienceHandler) retries transient failures, and you can disable retries for unsafe methods (DisableForUnsafeHttpMethods()). Browsers automatically retry idempotent requests on some connection failures; HTTP/2 GOAWAY handling also relies on it.

5. Caching rules

GET and HEAD responses are cacheable by default when freshness information is present (Cache-Control: max-age, Expires) or heuristically. POST responses are cacheable only with explicit freshness and a Content-Location, which almost nobody uses. A successful PUT, PATCH, POST or DELETE must invalidate cached entries for the target URI.

6. ASP.NET Core mapping

MapGet, MapPost, MapPut, MapPatch, MapDelete and MapMethods add HttpMethodMetadata. If a path matches but the method doesn't, routing returns 405 Method Not Allowed with an Allow header. HEAD is not routed to GET automatically for Minimal APIs; you map it with MapMethods(path, ["GET", "HEAD"], ...) or let a framework layer handle it.

Try it yourself

  1. Map the same route with MapGet only, then call it with curl -X DELETE -i and inspect the 405 and Allow header.
  2. Write an integration test with WebApplicationFactory that sends the same PUT three times and asserts the stored state is identical.
  3. Configure AddStandardResilienceHandler with options.Retry.DisableForUnsafeHttpMethods() and log which calls get retried.
  4. Create a GET endpoint that increments a counter and paste its URL into a chat app with link previews: count the hits.

💻 Code

Endpoints that respect method semantics, plus a client-side resilience handler that retries only idempotent methods.

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

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var orders = new ConcurrentDictionary<Guid, Order>();

app.MapGet("/orders/{id:guid}", (Guid id) =>
    orders.TryGetValue(id, out var o) ? Results.Ok(o) : Results.NotFound());

// POST: server assigns the id; not idempotent.
app.MapPost("/orders", (CreateOrder cmd) =>
{
    var order = new Order(Guid.NewGuid(), cmd.CustomerId, "Pending");
    orders[order.Id] = order;
    return Results.Created($"/orders/{order.Id}", order);
});

// PUT: client names the id; repeating it gives the same state.
app.MapPut("/orders/{id:guid}", (Guid id, ReplaceOrder body) =>
{
    var created = !orders.ContainsKey(id);
    var order = new Order(id, body.CustomerId, body.Status);
    orders[id] = order;
    return created ? Results.Created($"/orders/{id}", order) : Results.Ok(order);
});

// DELETE: idempotent in effect; the response may differ on repeat.
app.MapDelete("/orders/{id:guid}", (Guid id) =>
    orders.TryRemove(id, out _) ? Results.NoContent() : Results.NotFound());

app.Run();

public sealed record Order(Guid Id, int CustomerId, string Status);
public sealed record CreateOrder(int CustomerId);
public sealed record ReplaceOrder(int CustomerId, string Status);
// Client side: retry transient failures, but never blindly for POST/PATCH.
// Package: Microsoft.Extensions.Http.Resilience
builder.Services.AddHttpClient("orders", c => c.BaseAddress = new Uri("https://orders.internal"))
    .AddStandardResilienceHandler(options =>
    {
        options.Retry.DisableForUnsafeHttpMethods(); // POST, PATCH, CONNECT are not retried
    });

⚠ Common mistakes

  • Mistake: Changing state on GET (GET /orders/42/cancel). Why it is wrong: Crawlers, prefetchers, link previews and caches assume GET is safe and will trigger it. Instead: Use POST (or PATCH/DELETE) for anything with side effects.
  • Mistake: Believing idempotent means "returns the same response". Why it is wrong: A repeated DELETE can return 404; idempotency is about server state. Instead: Define it as "the same effect" and test the state.
  • Mistake: Using PUT for partial updates. Why it is wrong: PUT means replace; omitted fields should be reset, and clients may rely on that. Instead: Use PATCH for partial changes.
  • Mistake: Retrying POST on timeout in a client or gateway. Why it is wrong: The first attempt may have succeeded, creating duplicates (orders, payments). Instead: Retry only idempotent methods, or add an idempotency key.
  • Mistake: Sending filter criteria in a GET body. Why it is wrong: The body has no defined semantics and is often stripped. Instead: Query string, or POST /orders/search.
  • Mistake: Using POST for every operation. Why it is wrong: You lose caching, safe retries and self-describing semantics. Instead: Pick the method by its meaning.

🏛 Senior insight: trade-offs

The senior point is that method semantics are not style: they are what lets infrastructure you don't control behave correctly. A CDN caches GETs, a gateway retries PUTs, a browser preflights non-simple requests. When you get the method right you get those behaviours for free; when you get it wrong you get duplicate side effects in production.

In microservices this compounds. A service-to-service call usually passes through a client resilience handler, a service mesh sidecar and maybe a gateway, and each layer may retry. If a POST that charges a card is retried at three layers with three attempts each, one user click can become up to 27 charges. So either the method is idempotent, or the operation carries an idempotency key that every layer forwards, and retries are configured at one layer only.

Operation shape Method Why Watch out
Read, no side effects GET Cacheable, safe to retry Keep URLs free of personal data
Create, server assigns id POST Not idempotent, so add an idempotency key if retries matter Return 201 + Location
Create/replace, client owns id PUT Idempotent, retry-safe Must send the full representation
Partial update PATCH Small payloads Not idempotent by default; use If-Match for concurrency
Remove DELETE Idempotent Decide whether the repeat returns 204 or 404 and document it

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency or status codes Why: Checks broader HTTP knowledge from a backend point of view
    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 says POST is not idempotent Why: Checks whether they know idempotency keys and how to store and replay responses
    How to answer

    Have the client send a unique Idempotency-Key header per logical operation (one checkout attempt, not one HTTP attempt), and scope keys per client or API key so one caller can't replay another's. The server stores the key with a hash of the request and the response, atomically with the side effect (same transaction, or a unique constraint on the key). A repeat with the same key and body returns the stored response; the same key with a different body returns 422; a concurrent duplicate gets 409 until the first completes. Keys expire after a documented window such as 24 hours, enforced with a TTL (Redis) or a cleanup job (SQL). Log key reuse and mismatches so replay attempts and buggy clients show up in monitoring.

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me