10.3 — HTTP Status Codes That Actually Get Asked About¶
← Roadmap · Section: 10. Web API Design and REST Prev: 10.2 HTTP verbs and idempotency · Next: 10.4
[ApiController]
Markers: 🔥 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A status code is the three-digit number that tells the client what happened, in a way every client, proxy and cache understands without reading your response body.
- 2xx it worked · 3xx look elsewhere · 4xx the client's fault · 5xx ours.
- The four that get asked: 401 vs 403, 400 vs 422, 404 vs 204, 409 vs 400.
- Returning 200 with
{"success": false}is the anti-pattern. It makes every client parse the body to find out if the call worked.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Status code | a three-digit number | The machine-readable outcome of a request. |
| 200 OK | 2xx success | It worked, and there is a body. |
| 201 Created | 2xx success | A resource was created. Should carry a Location header. |
| 202 Accepted | 2xx success | Accepted for processing; not done yet. |
| 204 No Content | 2xx success | It worked, and there is deliberately no body. |
| 400 Bad Request | 4xx client error | The request is malformed or fails validation. |
| 401 Unauthorized | 4xx client error | ⚠️ Misnamed — it means unauthenticated. |
| 403 Forbidden | 4xx client error | We know who you are; you still may not. |
| 404 Not Found | 4xx client error | No such resource. |
| 405 Method Not Allowed | 4xx client error | The path exists, the verb does not. |
| 409 Conflict | 4xx client error | Valid request, but it conflicts with current state. |
| 422 Unprocessable Content | 4xx client error | Syntactically fine, semantically wrong. |
| 429 Too Many Requests | 4xx client error | Rate limited. |
| 500 Internal Server Error | 5xx server error | We broke. Unhandled exception. |
| 503 Service Unavailable | 5xx server error | Temporarily down or overloaded. Retryable. |
ProblemDetails |
a C# class (RFC 7807) | The standard error body shape in ASP.NET Core. |
The concept¶
A status code is the API's contract with everything between it and the caller. Load balancers retry on 503. Caches store 200 and 404 and skip 500. Client libraries throw on 4xx. Monitoring alerts on 5xx rate.
All of that works because the number means something before anyone parses the body.
⚠️ Which is exactly why 200 OK with {"success": false, "error": "..."} is a real problem.
It is not just untidy:
- Every client must parse the body to find out whether the call worked.
- Retry policies see success and never retry.
- Monitoring sees 100% success while users are failing.
- Caches happily store the error and serve it to everyone.
The status code is the part of the response that the infrastructure can act on. Throwing it away means throwing away everything HTTP gives you for free.
How it works¶
The families¶
| Family | Meaning | Who is at fault | Retry? |
|---|---|---|---|
| 1xx | Informational | — | — |
| 2xx | Success | — | — |
| 3xx | Redirect / not modified | — | Follow it |
| 4xx | Client error | The caller | ❌ Not without changing the request |
| 5xx | Server error | Us | ✅ Usually |
The 4xx/5xx split is the one that matters operationally. 4xx means "you sent something wrong — sending it again will fail again". 5xx means "we failed — try again later". Return 500 for a validation failure and clients will retry a request that can never succeed; return 400 for a database outage and clients will give up on something that would have worked in ten seconds.
401 vs 403 — the most-asked pair¶
⚠️ 401 is misnamed. It says "Unauthorized" but it means unauthenticated.
| 401 Unauthorized | 403 Forbidden | |
|---|---|---|
| Means | "I don't know who you are" | "I know who you are, and no" |
| Cause | No token, expired token, bad token | Valid identity, insufficient permission |
| Client should | Log in / refresh the token | Not retry — nothing will change |
| Required header | WWW-Authenticate |
— |
return Unauthorized(); // 401 — authenticate first
return Forbid(); // 403 — authenticated, but not allowed
⚠️ Returning 401 to an already-authenticated user causes a redirect loop. Cookie authentication sees 401, redirects to the login page, the user is already logged in, gets sent back to the resource, gets 401 again — forever (16.1).
⚠️ And Forbid() is not the same as StatusCode(403). Forbid() runs the authentication
scheme's forbid handler, which may redirect to an access-denied page. In an API you often want the
bare status code; in an MVC app you usually want the handler.
The information-disclosure wrinkle. Sometimes 404 is the right answer to an authorization
failure. GET /orders/999 where order 999 belongs to another customer: 403 confirms that order 999
exists. 404 does not. For anything where the ID space is enumerable and existence is sensitive,
404 is the more secure answer — a deliberate choice worth being able to explain
(17.12).
400 vs 422 — the pedantic one¶
| 400 Bad Request | 422 Unprocessable Content | |
|---|---|---|
| Means | I cannot parse this | I parsed it; it makes no sense |
| Example | Malformed JSON, wrong type | endDate before startDate |
⚠️ In practice most APIs use 400 for both, and that is defensible. ASP.NET Core's
[ApiController] automatic validation returns 400, not 422
(10.4).
The honest interview answer: 422 is technically more precise for business-rule failures, but 400 is what the framework does by default and what most clients expect. Consistency beats precision. Do not silently mix them.
404 vs 204 vs 200-with-empty-list¶
Three different "nothing here" situations, three different answers:
// Single resource that does not exist → 404
var order = await _orders.FindAsync(id, ct);
if (order is null) return NotFound();
// Collection with no matches → 200 with an EMPTY ARRAY, not 404
// The collection /orders EXISTS. It just currently contains nothing.
return Ok(new List<OrderDto>());
// Successful operation with nothing to say → 204
await _orders.DeleteAsync(id, ct);
return NoContent();
⚠️ Returning 404 for an empty search result is a common mistake. /orders?status=cancelled
with no cancelled orders is a successful query that found nothing — 200 with []. A 404 tells
the client the endpoint does not exist, and forces every caller to special-case it.
405 and 409 — the two people forget¶
405 Method Not Allowed happens automatically: the route template matches but no action handles
that verb. DELETE /api/orders when only GET and POST exist gives 405, not 404. Worth knowing
because "why am I getting 405?" almost always means a missing [HttpX] attribute
(8.7).
409 Conflict is for a request that is perfectly valid but conflicts with current state:
- Creating a user with an email that already exists.
- A concurrency clash — someone else edited the row first (13.13).
- Cancelling an order that has already shipped.
⚠️ 409 is under-used. Most APIs return 400 for all of these, which tells the client "you sent something wrong" when actually they sent something perfectly reasonable that no longer applies.
The deeper detail — the ones worth knowing¶
| Code | When |
|---|---|
| 202 Accepted | Long-running work queued. Return a Location pointing at a status resource. |
| 304 Not Modified | Answer to a conditional GET — the client's cached copy is fine (10.13). |
| 412 Precondition Failed | If-Match did not match. Optimistic concurrency over HTTP. |
| 415 Unsupported Media Type | Wrong Content-Type — text/plain at a JSON endpoint (10.5). |
| 429 Too Many Requests | Rate limited. Include Retry-After (17.10). |
| 503 Service Unavailable | Down for maintenance or overloaded. Also include Retry-After. |
⚠️ 418 I'm a teapot is a joke from a 1998 April Fools RFC. It occasionally shows up in interviews as a trick — know it is real, know it is not for use.
⚠️ A 500 should never carry a stack trace in production. It leaks framework versions, file
paths and sometimes connection strings. Return a ProblemDetails with a correlation ID and put the
detail in the logs (10.8, 18.4).
Code¶
[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
private readonly IOrderService _orders;
public OrdersController(IOrderService orders) => _orders = orders;
// 200 with an empty array when nothing matches — NOT 404.
// The collection exists; it is simply empty right now.
[HttpGet]
public async Task<ActionResult<IReadOnlyList<OrderDto>>> List(
[FromQuery] string? status, CancellationToken ct)
=> Ok(await _orders.SearchAsync(status, ct));
[HttpGet("{id:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
{
var order = await _orders.FindAsync(id, ct);
if (order is null) return NotFound();
// ⚠️ 404, not 403 — 403 would confirm that order id exists to someone
// probing sequential IDs. Deliberate information hiding.
if (order.CustomerId != User.GetCustomerId()) return NotFound();
return Ok(order);
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<ActionResult<OrderDto>> Create(CreateOrderRequest req, CancellationToken ct)
{
// [ApiController] already returned 400 for malformed input before we got here
var result = await _orders.CreateAsync(req, ct);
if (result.Status == CreateStatus.DuplicateReference)
{
// 409, not 400 — the request is valid, it just conflicts with existing state
return Conflict(new ProblemDetails
{
Title = "Duplicate order reference",
Detail = $"An order with reference '{req.Reference}' already exists.",
Status = StatusCodes.Status409Conflict
});
}
return CreatedAtAction(nameof(Get), new { id = result.Order!.Id }, result.Order);
}
// 202 — queued, not finished. Location points at where to poll.
[HttpPost("{id:int}/export")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public async Task<IActionResult> Export(int id, CancellationToken ct)
{
var jobId = await _orders.QueueExportAsync(id, ct);
return AcceptedAtAction(nameof(GetExportStatus), new { id, jobId }, null);
}
[HttpGet("{id:int}/export/{jobId:guid}")]
public async Task<ActionResult<ExportStatusDto>> GetExportStatus(
int id, Guid jobId, CancellationToken ct)
=> Ok(await _orders.GetExportStatusAsync(jobId, ct));
// 204 — it worked and there is deliberately nothing to send back
[HttpDelete("{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Delete(int id, CancellationToken ct)
{
await _orders.DeleteAsync(id, ct);
return NoContent();
}
}
The [ProducesResponseType] attributes are not decoration — they are what OpenAPI reads to
document the possible outcomes, and what generated clients turn into typed results
(10.9).
Handling 5xx globally rather than per-action:
app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
{
var feature = context.Features.Get<IExceptionHandlerFeature>();
// Map known exception types to the right 4xx; everything else is genuinely a 500
var (status, title) = feature?.Error switch
{
NotFoundException => (404, "Resource not found"),
ConflictException => (409, "Conflict with current state"),
ValidationException => (400, "Validation failed"),
UnauthorizedAccessException => (403, "Forbidden"),
_ => (500, "An unexpected error occurred")
};
context.Response.StatusCode = status;
await context.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = status,
Title = title,
// ⚠️ NEVER the exception message on a 500 — it leaks internals.
// The correlation ID is how support finds the real detail in the logs.
Detail = status == 500 ? null : feature?.Error.Message,
Extensions = { ["traceId"] = context.TraceIdentifier }
});
}));
Interview questions¶
Q: What is the difference between 401 and 403?
401 is misnamed — it says Unauthorized but means unauthenticated: we do not know who you are,
because there is no token or it is invalid, and the response should carry a WWW-Authenticate
header. 403 means we do know who you are and you still cannot do this, so retrying with the same
credentials is pointless. The practical consequence is that returning 401 to a user who is already
logged in causes a redirect loop under cookie auth. Worth adding that for a resource belonging to
someone else, 404 is sometimes the better answer than 403, because 403 confirms the resource exists
to someone enumerating IDs.
Q: When would you return 409 rather than 400?
400 means the request itself is wrong — malformed, missing a field, wrong type. 409 means the request is perfectly valid but conflicts with current state: creating a user with an email that is already taken, cancelling an order that has already shipped, or an optimistic concurrency clash where someone else saved first. The distinction matters to the client, because a 400 says "fix your request" while a 409 says "your request was fine, the world changed underneath it" — often the client's correct response is to refetch and show the user what happened.
Q: What is wrong with returning 200 with a success flag in the body?
It throws away the part of the response that infrastructure can act on. Retry policies see success and never retry a failure; monitoring reports a 100% success rate while users are erroring; caches store the failure and serve it to everyone; and every client has to parse the body to find out whether the call worked. The status code is the machine-readable outcome — the body is for detail, not for the verdict.
Q: What do you return when a search finds nothing?
200 with an empty array. The collection endpoint exists and the query succeeded — it just matched
nothing, which is a normal result, not an error. 404 is for a single resource that does not exist,
like /orders/999. Returning 404 for an empty result forces every caller to special-case it and
conflates "no matches" with "wrong URL".
Traps ⚠️¶
- 200 with
{"success": false}defeats retries, caching and monitoring. - 401 for an authenticated user causes a cookie-auth redirect loop.
- 403 where 404 is safer confirms a resource exists to someone enumerating IDs.
- 404 for an empty collection. Return 200 with
[]. - 500 for validation failures makes clients retry something that can never succeed.
- 400 for a transient outage makes clients give up on something retryable. Use 503.
- Stack traces in a 500 body leak paths, versions and sometimes credentials.
- 429 or 503 without
Retry-Afterleaves clients guessing. Forbid()vsStatusCode(403)— the first runs the scheme's handler and may redirect.- Mixing 400 and 422 arbitrarily. Pick one convention.
- 201 without a
Locationheader — the client cannot find what you created. - Unexpected 405 almost always means a missing
[HttpX]attribute.
Related¶
- 10.2 HTTP verbs — which code goes with which verb
- 10.4
[ApiController]— why validation returns 400 - 10.8
ProblemDetails— the standard error body - 10.9 OpenAPI — documenting the codes you return
- 16.1
[Authorize]— where 401 and 403 come from - 17.12 IDOR — 404 as information hiding
- 13.13 Concurrency — where 409 comes from
- 17.10 Rate limiting — 429 and
Retry-After