Choosing status codes as part of the API contract: success codes, client error distinctions (400/422, 401/403, 404/410, 409, 412, 429) and server/gateway errors (500, 502, 503, 504).
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.
"I treat status codes as part of the contract, because clients, gateways, retry policies and dashboards all branch on them without reading the body. For success I use 200 when I return a body, 201 Created with a Location header when a resource was created, 202 Accepted when I've queued work and return a status URL, and 204 when there's nothing to say, like a successful DELETE.
For client errors the pairs matter. 400 is malformed or invalid input; some teams use 422 for input that parses but breaks a business rule. ASP.NET Core's
[ApiController]returns 400 with aValidationProblemDetailsby default, so I usually stick with 400 for validation and document it. 401 means 'I don't know who you are', and comes withWWW-Authenticate; 403 means 'I know who you are and you can't do this'. 404 is not found, and I also return it when revealing that a resource exists would leak information; 410 is 'it existed and it's gone for good'. 409 is a conflict with current state, like a duplicate order number; 412 is a failedIf-Matchon an ETag; 429 is rate limiting with aRetry-After.On the server side, 500 means my code broke, 502 means an upstream gave me garbage, 503 means I'm overloaded or in maintenance and the client should retry later, and 504 means an upstream timed out. Getting these right matters operationally: retry policies retry 503 and 504 but shouldn't retry 400, and alerts fire on 5xx, not 4xx. The mistake I see is returning 200 with
{\"success\": false}. Monitoring shows 100% success while customers fail."
| Code | Use when | Headers / body |
|---|---|---|
| 200 OK | Read or update with a body | Representation |
| 201 Created | New resource | Location: /orders/42, usually the resource |
| 202 Accepted | Work queued, not done | Location or body link to a status resource |
| 204 No Content | Success, nothing to return | No body |
| 304 Not Modified | Conditional GET matched ETag | No body |
| Pair | Difference |
|---|---|
| 400 vs 422 | Malformed/invalid vs semantically invalid; choose one convention for validation |
| 401 vs 403 | Not authenticated vs not authorised |
| 404 vs 410 | Unknown (or hidden) vs permanently removed |
| 409 vs 412 | Conflicts with state vs explicit precondition header failed |
| 413 / 415 | Payload too large / unsupported Content-Type |
| 429 | Rate limited; send Retry-After |
| Code | Meaning | Retry? |
|---|---|---|
| 500 | Unhandled error in this service | Usually not automatically |
| 502 | Invalid response from upstream | Sometimes |
| 503 | Temporarily unavailable / overloaded | Yes, honour Retry-After |
| 504 | Upstream timed out | Yes, if the operation is idempotent |
An [internal orders API] returned 200 with {\"success\": false} for failures. Application Insights showed 99.9% success while [about 4%] of checkouts failed. Switching to proper 4xx/5xx codes with ProblemDetails made the failure rate visible on the dashboard within a day and let the gateway's retry policy stop retrying validation errors.
Checks that the candidate can pick precise status codes and understands how clients and infrastructure act on them.
Green flags
Red flags
1xx informational 100 Continue, 101 Switching Protocols, 103 Early Hints
2xx success 200, 201, 202, 204, 206 Partial Content
3xx redirection 301, 302, 303 See Other, 304 Not Modified, 307, 308
4xx client error the client must change something before retrying
5xx server error the server failed; the same request may succeed later
Clients that don't know a specific code treat it as the x00 of its class, which is why the class matters more than the exact number.
201 Created should carry a Location header with the new resource's URI. In ASP.NET Core: TypedResults.Created($"/orders/{id}", dto) or CreatedAtRoute/CreatedAtAction in MVC. Clients can follow it without parsing the body.
POST /reports -> 202 Accepted, Location: /reports/jobs/9f3
GET /reports/jobs/9f3 -> 200 {status: "Running"}
GET /reports/jobs/9f3 -> 303 See Other, Location: /reports/77 (or 200 with a link)
RFC 9110 defines 422 Unprocessable Content (previously WebDAV-only). Both are valid for validation. ASP.NET Core's automatic model validation returns 400 with ValidationProblemDetails; you can configure InvalidModelStateResponseFactory to return 422. Consistency across services matters more than which you choose.
The authentication middleware's challenge produces 401 (with WWW-Authenticate: Bearer); forbid produces 403. RequireAuthorization() returns 401 for anonymous users and 403 for authenticated users who fail the policy. Returning 404 instead of 403 for resources a user must not know exist (another customer's order) avoids an enumeration leak.
Client -> Front Door / APIM -> App Service -> SQL
502: App Service returned a broken response or reset
503: no healthy instance / maintenance / app overloaded
504: App Service didn't answer within the gateway timeout
500: the app threw
When you see 502/504 in client logs but no failed requests in the app's own telemetry, the problem is between the gateway and the app (timeouts, cold starts, port mismatch).
Every 4xx/5xx should carry application/problem+json (RFC 9457) with type, title, status, detail, instance, plus extensions such as traceId and an error code. AddProblemDetails() makes the framework produce them for unhandled exceptions and empty error responses.
TypedResults.Created, Accepted, NoContent, Conflict, UnprocessableEntity and inspect them with curl -i.AddProblemDetails() and UseStatusCodePages() and compare the 404 body before and after.RequireAuthorization("Admin") and call it anonymously and as a non-admin to see 401 vs 403.requests | summarize count() by resultCode and spot any 200s that hide failures.Returning precise status codes with TypedResults, so the codes also appear in OpenAPI metadata.
// Program.cs (.NET 10)
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(); // RFC 9457 bodies for errors
builder.Services.AddSingleton<OrderStore>();
var app = builder.Build();
app.UseExceptionHandler(); // unhandled -> 500 problem+json
app.UseStatusCodePages(); // empty 4xx -> problem+json
app.MapPost("/orders", Results<Created<OrderDto>, ValidationProblem, Conflict<ProblemDetailsDto>> (
CreateOrder cmd, OrderStore store) =>
{
if (cmd.Quantity <= 0)
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
["quantity"] = ["Quantity must be at least 1."]
}); // 400 with field errors
if (store.Exists(cmd.OrderNumber))
return TypedResults.Conflict(new ProblemDetailsDto("order-number-taken",
$"Order number {cmd.OrderNumber} already exists.")); // 409
var dto = store.Add(cmd);
return TypedResults.Created($"/orders/{dto.Id}", dto); // 201 + Location
});
app.MapPost("/reports", () =>
TypedResults.Accepted("/reports/jobs/9f3", new { jobId = "9f3" })); // 202
app.MapDelete("/orders/{id:int}", Results<NoContent, NotFound> (int id, OrderStore store) =>
store.Remove(id) ? TypedResults.NoContent() : TypedResults.NotFound());
app.Run();
public sealed record CreateOrder(string OrderNumber, int Quantity);
public sealed record OrderDto(int Id, string OrderNumber, int Quantity);
public sealed record ProblemDetailsDto(string Code, string Detail);
public sealed class OrderStore
{
private readonly Dictionary<int, OrderDto> _orders = [];
private int _next = 1;
public bool Exists(string number) => _orders.Values.Any(o => o.OrderNumber == number);
public OrderDto Add(CreateOrder c) { var o = new OrderDto(_next++, c.OrderNumber, c.Quantity); _orders[o.Id] = o; return o; }
public bool Remove(int id) => _orders.Remove(id);
}
{"success": false}. Why it is wrong: Monitoring, retries and clients see success; failures become invisible. Instead: Use the right 4xx/5xx with a ProblemDetails body.Location header. Why it is wrong: Clients have to guess or parse the body to find the resource. Instead: TypedResults.Created(uri, dto).Retry-After. Why it is wrong: Clients retry immediately and make the overload worse. Instead: Send Retry-After in seconds.Status codes drive automation: retry policies, circuit breakers, alerts, SLOs and caches. A senior designs the code set with those consumers in mind. 4xx should mean "the client must change the request", so it should never page anyone; 5xx should mean "we failed", so it counts against the SLO. Getting that split wrong either hides outages or wakes people for user typos.
| Decision | Option | When it fits | Cost |
|---|---|---|---|
| Validation code | 400 | Default in ASP.NET Core; simple | Mixes malformed and semantic errors |
| Validation code | 422 | Clear split between syntax and business rules | Must override the default factory |
| Unauthorised resource | 403 | Internal APIs where existence isn't secret | Leaks existence |
| Unauthorised resource | 404 | Multi-customer data | Harder to debug for legitimate users |
| Async work | 202 + status URL | Work > a few seconds | Client must poll or subscribe |
ProblemDetails is the standard JSON shape for HTTP API errors, defined by RFC 9457 (which replaced RFC 7807): type, title, status, detail, instance, plus extension members, served as application/problem+json. ValidationProblemDetails adds an errors dictionary per field. In ASP.NET Core, AddProblemDetails() registers IProblemDetailsService, which the framework uses wherever it writes an error body: UseExceptionHandler for unhandled exceptions, UseStatusCodePages for empty 404s/401s, and the developer exception page. CustomizeProblemDetails adds a traceId and anything else to every response; an IExceptionHandler maps known exceptions to specific codes with a stable errorCode extension. The trade-off: one consistent contract for every error, but you must make sure no internal detail leaks.
HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.
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.Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.Returning 403 confirms the resource exists, which lets an attacker enumerate ids (for example other customers' order numbers). Returning 404 hides existence, the safer default for customer-owned data and in line with Privacy Act obligations. Implement it in the authorisation layer: resource-based authorisation (IAuthorizationService with a requirement checking ownership, plus scopes or claims from the JWT) or queries filtered by the caller's customer id, so another customer's record simply isn't found. The trade-off is usability: legitimate users and support staff get a less helpful error, so log the real reason server-side with the trace id and return that trace id in the ProblemDetails body. Keep 403 where existence isn't secret, such as a missing scope on an admin endpoint.
Last updated 23 Nov 2026.