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.
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.
"I start by separating collection resources from item resources.
/ordersis 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
Locationheader pointing at the new item; in ASP.NET Core that'sTypedResults.Created($"/orders/{id}", dto)orCreatedAtRoute. 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-Matchwith an ETag from arowversioncolumn. Choosing POST or PUT is really choosing who owns identity and how retries behave."
| 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 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 |
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.
Checks that the candidate maps CRUD to HTTP precisely and understands that POST vs PUT is about id ownership and idempotency.
Green flags
Location on createRed flags
/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.
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.
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.
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.
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).
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.
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).POST /orders with a simulated client timeout and retry; count the rows.Location header produced by TypedResults.Created and CreatedAtRoute with curl -i.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);
}
}
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.POST /orders/{id} to update. Why it is wrong: It hides the semantics and loses idempotency. Instead: PUT or PATCH on the item.If-Match with an ETag from rowversion, return 412 when stale.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 |
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:
null means remove. Simple, but can't express array edits or set a value to null.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.
The status code tells clients and infrastructure what happened before they read the body, so it must be exact.
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.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.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.
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.
Last updated 23 Nov 2026.