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

📚 Interview question

How do you map CRUD operations onto HTTP? When should a create be a POST to a collection and when a PUT to a known URI, how do you implement an upsert with PUT, and what is the difference between a collection resource and an item resource?

Mapping create, read, update and delete to HTTP methods and status codes: POST to a collection vs PUT to an item, upsert semantics, collection vs item resources, and the responses each should return.

Junior Theory Intermediate aspnet-core crud http-methods rest upsert web-api

🎯 Key points

  • Collection resource (/orders) vs item resource (/orders/{id})
  • POST /orders when the server assigns the id: 201 Created + Location header
  • PUT-create (upsert) only when the client owns the id (GUID or natural key): 201 if new, 200/204 if replaced; idempotent
  • PUT replaces the whole representation; partial changes use PATCH
  • PUT replacing an existing item needs concurrency control: require If-Match with an ETag from rowversion, 412 if stale, 428 if missing
  • GET collection 200 with paging; GET item 200 or 404
  • DELETE /orders/{id}: 204, repeat may be 204 or 404 (idempotent in effect)
  • Document create/replace/repeat behaviour (201 vs 204, repeat DELETE result) in the OpenAPI document

⏱ 30-second answer

Model a collection (/orders) and items (/orders/{id}). Read is GET on either. Create is POST /orders when the server assigns the id, returning 201 Created with a Location header. When the client owns the id (a GUID or natural key), create with PUT /orders/{id}: that is an upsert, returning 201 if new and 200/204 if replaced, and it is idempotent, so it is safe to retry. Update is PUT (full replacement) or PATCH (partial). Delete is DELETE /orders/{id}, returning 204.

The trade-off: POST is simpler and keeps id generation on the server, but a retried POST can create duplicates; PUT is retry-safe but makes clients responsible for ids and for sending the full representation.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by separating collection resources from item resources. /orders is the collection: GET lists it, POST adds to it. /orders/{id} is one item: GET reads it, PUT replaces it, PATCH changes part of it, DELETE removes it.

For creates, the question is who owns the identifier. If the server generates it, say an identity column in Azure SQL, I use POST to the collection and return 201 Created with a Location header pointing at the new item; in ASP.NET Core that's TypedResults.Created($"/orders/{id}", dto) or CreatedAtRoute. If the client owns the id, such as a GUID it generated offline or a natural key like a product SKU, I use PUT to /orders/{id}. PUT means 'make the resource at this URI look like this', so if it doesn't exist it's created, which is an upsert. I return 201 for a create and 200 or 204 for a replace. Because PUT is idempotent, a mobile client on a flaky connection can retry it without making duplicates.

The mistake I see is using PUT for partial updates. PUT is a full replacement, so a client that sends only the fields it changed should expect the others to be cleared. For partial changes I use PATCH. The other mistake is a PUT upsert without concurrency control: two clients replacing the same item silently overwrite each other, so I add If-Match with an ETag from a rowversion column. Choosing POST or PUT is really choosing who owns identity and how retries behave."


CRUD mapping

Operation Method and URI Success Common failures
List GET /orders?status=open&pageSize=50 200 (paged) 400 bad filter
Read GET /orders/{id} 200 404
Create (server id) POST /orders 201 + Location 400/422, 409 duplicate
Create or replace (client id) PUT /orders/{id} 201 new / 200 or 204 replaced 412 precondition failed
Partial update PATCH /orders/{id} 200 / 204 404, 409, 412
Delete DELETE /orders/{id} 204 404 (or 204 on repeat)

POST vs PUT for create

POST to collection PUT to item
Who picks the id Server Client
Idempotent No Yes
Retry after timeout May duplicate (needs idempotency key) Safe
Body Create command / partial data Full representation
Typical use Orders, payments, comments Settings, documents with GUIDs, sync from offline clients

Production example

An [offline-first field app] created inspection records with POST /inspections. On poor mobile coverage, retries produced [~3%] duplicate records. Switching to client-generated GUIDs and PUT /inspections/{id} made retries idempotent, and duplicates dropped to zero within a release.

🔍 What the interviewer is checking

Checks that the candidate maps CRUD to HTTP precisely and understands that POST vs PUT is about id ownership and idempotency.

Green flags

  • Distinguishes collection and item resources
  • Returns 201 with Location on create
  • Explains PUT as create-or-replace at a known URI and why it's retry-safe
  • Mentions concurrency control on PUT (If-Match, rowversion)

Red flags

  • Uses PUT for partial updates
  • "POST is for create, PUT is for update" with no nuance
  • Uses POST for every operation

📚 Learn in depth

1. Collection and item resources

/orders            collection   GET (list), POST (add)
/orders/{id}       item         GET, PUT, PATCH, DELETE
/orders/{id}/lines sub-collection of an item

RFC 9110 defines POST as "process the representation according to the resource's own semantics". For a collection, that conventionally means "add a member", and the server tells you where it went with Location.

2. PUT semantics

PUT asks the server to make the target resource's state equal the enclosed representation. If the resource didn't exist and the server allows it, PUT creates it (201); otherwise it replaces it (200 with a body, or 204). Because the target URI is fixed and the state is fully specified, sending it twice gives the same result: idempotent. PUT-create only makes sense when the client owns the identifier; if the server assigns ids, the client can't know the URI in advance and must POST to the collection.

3. Concurrency: two different problems

Lost update on replace. Client A and B both GET product SKU-123 (ETag "v1"). A PUTs a new price, the row version becomes "v2". B then PUTs its stale copy. Without a check, B silently overwrites A.

A: GET  -> ETag "v1"          B: GET -> ETag "v1"
A: PUT If-Match "v1" -> 204 (now "v2")
B: PUT If-Match "v1" -> 412 Precondition Failed -> B re-reads, merges, retries

The server sets the entity's RowVersion original value to the ETag the client sent, so EF Core adds WHERE RowVersion = @original to the UPDATE. Zero rows affected raises DbUpdateConcurrencyException, which the API maps to 412. To stop clients skipping the check, a replace without If-Match returns 428 Precondition Required (RFC 6585). Don't automatically retry a 412 on the server: the client must decide how to merge.

Concurrent first-time create. Two PUTs for a new key can both see "not found" and both INSERT. The primary key makes one fail with a duplicate-key DbUpdateException (SQL error 2627/2601). Handle it by detaching the failed entity, re-reading the row and treating the request as a replace (which then goes through the If-Match rule), or by doing the upsert in SQL with MERGE ... WITH (HOLDLOCK) or INSERT ... WHERE NOT EXISTS under UPDLOCK, HOLDLOCK.

4. Why ids matter for retries

Client --POST /orders--> API (creates order 77) --X timeout-- Client
Client --POST /orders--> API (creates order 78)   duplicate!

Client --PUT /orders/9f3c...--> API (creates)    --X timeout--
Client --PUT /orders/9f3c...--> API (replaces with same data) no duplicate

Note the retried PUT-create in the second flow arrives without If-Match because the client never saw an ETag; a strict API answers 428 or treats an identical body as a no-op. Decide and document which.

5. Deletes

DELETE is idempotent in effect. Whether the second call returns 204 or 404 is your choice; document it. Soft delete is an implementation detail: the API should still behave as if the resource is gone (404 on GET).

6. Document the contract

In OpenAPI, list 201 and 204 for PUT, 412 and 428 for missing or stale preconditions, and the repeat-DELETE result. Client teams build retry logic from this.

Try it yourself

  1. Implement PUT /products/{sku} as an upsert with EF Core and write tests for create (201), replace (204), missing If-Match (428) and stale If-Match (412).
  2. Fire two concurrent first-time PUTs for the same key and observe the duplicate-key exception; then handle it.
  3. Call POST /orders with a simulated client timeout and retry; count the rows.
  4. Inspect the Location header produced by TypedResults.Created and CreatedAtRoute with curl -i.

💻 Code

Collection and item endpoints, including a PUT upsert that requires If-Match for replacements (optimistic concurrency with rowversion).

// Program.cs (.NET 10)
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ShopDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
builder.Services.AddProblemDetails();
var app = builder.Build();

var products = app.MapGroup("/products");

products.MapGet("/{sku}", async (string sku, HttpResponse res, ShopDb db, CancellationToken ct) =>
{
    var p = await db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Sku == sku, ct);
    if (p is null) return Results.NotFound();
    res.Headers.ETag = $"\"{Convert.ToBase64String(p.RowVersion)}\""; // the version the client must echo back
    return Results.Ok(new ProductDto(p.Sku, p.Name, p.Price));
});

// PUT = create or replace at a client-chosen key (idempotent).
products.MapPut("/{sku}", async (string sku, ProductBody body, HttpRequest req, ShopDb db, CancellationToken ct) =>
{
    var existing = await db.Products.FirstOrDefaultAsync(p => p.Sku == sku, ct);
    if (existing is null)
    {
        db.Products.Add(new Product { Sku = sku, Name = body.Name, Price = body.Price });
        try
        {
            await db.SaveChangesAsync(ct);
            return Results.Created($"/products/{sku}", new ProductDto(sku, body.Name, body.Price));
        }
        catch (DbUpdateException) // another request created it first (duplicate key)
        {
            return Results.Problem(statusCode: StatusCodes.Status409Conflict,
                title: "Product was created concurrently; GET it and retry with If-Match.");
        }
    }

    // Replacing an existing resource requires the ETag the client last saw.
    var ifMatch = req.Headers.IfMatch.ToString();
    if (string.IsNullOrEmpty(ifMatch))
        return Results.Problem(statusCode: StatusCodes.Status428PreconditionRequired, title: "If-Match header is required.");

    // EF Core adds WHERE RowVersion = @original to the UPDATE.
    db.Entry(existing).Property(p => p.RowVersion).OriginalValue = Convert.FromBase64String(ifMatch.Trim('"'));
    existing.Name = body.Name;   // full replacement: every field is set
    existing.Price = body.Price;
    try { await db.SaveChangesAsync(ct); }
    catch (DbUpdateConcurrencyException)
    {
        return Results.Problem(statusCode: StatusCodes.Status412PreconditionFailed, title: "The product changed; re-read it.");
    }
    return Results.NoContent();
});

products.MapDelete("/{sku}", async (string sku, ShopDb db, CancellationToken ct) =>
    await db.Products.Where(p => p.Sku == sku).ExecuteDeleteAsync(ct) > 0 ? Results.NoContent() : Results.NotFound());

app.Run();

public sealed class Product
{
    public required string Sku { get; set; }
    public required string Name { get; set; }
    public decimal Price { get; set; }
    public byte[] RowVersion { get; set; } = [];
}
public sealed record ProductBody(string Name, decimal Price);
public sealed record ProductDto(string Sku, string Name, decimal Price);

public sealed class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();
    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Product>().HasKey(p => p.Sku);
        b.Entity<Product>().Property(p => p.RowVersion).IsRowVersion();
        b.Entity<Product>().Property(p => p.Price).HasPrecision(18, 2);
    }
}

⚠ Common mistakes

  • Mistake: Using PUT for partial updates. Why it is wrong: PUT replaces the whole resource; omitted fields should be reset, and clients relying on the standard will lose data. Instead: Use PATCH for partial changes.
  • Mistake: Returning 200 with no Location after a POST create. Why it is wrong: The client can't find the new resource without parsing the body, and tooling expects 201. Instead: Return 201 Created with Location.
  • Mistake: Using POST /orders/{id} to update. Why it is wrong: It hides the semantics and loses idempotency. Instead: PUT or PATCH on the item.
  • Mistake: Accepting PUT to a client id without concurrency control. Why it is wrong: Last writer wins and silently overwrites others' changes. Instead: Require If-Match with an ETag from rowversion, return 412 when stale.
  • Mistake: Letting the client choose server-owned ids via PUT (e.g. sequential integers). Why it is wrong: Clients can collide or guess ids. Instead: Only allow PUT-create with GUIDs or genuine natural keys.
  • Mistake: Retrying POST creates blindly. Why it is wrong: The first attempt may have succeeded, creating duplicates. Instead: Use PUT with a client id, or an idempotency key on POST.

🏛 Senior insight: trade-offs

Choosing between POST and PUT for create is a decision about identity ownership and retry behaviour, not style. Client-generated GUIDs (ideally sequential, like Guid.CreateVersion7() in .NET 9+, to limit index fragmentation in SQL Server) make PUT-create natural and retry-safe, which is valuable for mobile and offline sync. For aggregates where the server must control numbering (invoice numbers with legal sequencing requirements), POST plus an idempotency key is better.

I also make the repeat behaviour of DELETE and PUT explicit in the OpenAPI document, because client teams will write retry logic around it.

Approach When it fits Cost When not
POST create, server id Server owns numbering, simple clients Retries can duplicate Flaky networks without idempotency keys
PUT upsert, client id Offline clients, sync, natural keys Client generates ids; full payload Server-controlled sequences (invoice numbers)
POST + Idempotency-Key Payments, orders Key storage and expiry Simple internal CRUD where duplicates are harmless

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions PATCH or partial updates Why: Checks partial update semantics and JSON Patch vs Merge Patch
    How to answer

    PUT replaces the whole resource with the representation sent, so anything omitted is reset; it is idempotent. PATCH sends only the changes.

    Two standard PATCH formats exist:

    • JSON Merge Patch (RFC 7396): send a partial document; null means remove. Simple, but can't express array edits or set a value to null.
    • JSON Patch (RFC 6902): an ordered list of operations (replace, add, remove, test). Precise, but verbose.

    The hard part is missing vs null: a normal C# DTO can't tell them apart, so you read JsonElement/JsonNode or use JsonPatchDocument<T> (System.Text.Json-based since .NET 10). The trade-off: merge patch is friendlier for clients; JSON Patch is safer for arrays and conditional (test) updates.

  2. When: Candidate mentions 201, 204 or 404 Why: Checks status code choices for each CRUD outcome
    How to answer

    The status code tells clients and infrastructure what happened before they read the body, so it must be exact.

    • Success: 200 OK with a body, 201 Created plus a Location header, 202 Accepted for work that finishes later, 204 No Content when there's nothing to return.
    • Client errors: 400 bad input, 422 well-formed but semantically invalid, 401 not authenticated vs 403 not allowed, 404 not found vs 410 gone, 409 conflicts with current state, 412 a precondition like If-Match failed, 429 rate limited with Retry-After.
    • Server errors: 500 our bug, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.

    The trade-off is precision versus consistency: pick a small, documented set and use it the same way in every service.

  3. When: Candidate says POST creates can duplicate on retry Why: Checks how to make a non-idempotent POST create safe to retry
    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.

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me