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

📚 Interview question

How do you choose the right HTTP status code in an API? Explain 200 vs 201 (with Location) vs 202 vs 204, 400 vs 422, 401 vs 403, 404 vs 410, when to use 409, 412 and 429, and how 500 differs from 502, 503 and 504.

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).

Junior Theory Intermediate api-design aspnet-core http problem-details status-codes web-api

🎯 Key points

  • 2xx: 200 with body, 201 Created + Location, 202 Accepted for async work, 204 No Content
  • 400 malformed or invalid input; 422 well-formed but semantically invalid (pick one convention and document it)
  • 401 = not authenticated (with WWW-Authenticate); 403 = authenticated but not allowed
  • 404 not found (or hidden for authorisation); 410 gone permanently
  • 409 conflict with current state; 412 precondition (If-Match) failed; 429 too many requests + Retry-After
  • 500 bug in this service; 502 bad upstream response; 503 temporarily unavailable + Retry-After; 504 upstream timeout
  • Clients, retry policies and alerts branch on the code: 4xx = fix the request, 5xx = retry/alert
  • One documented code set across services, declared with TypedResults/Results<...> so OpenAPI lists every code; errors as ProblemDetails (RFC 9457)

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

🗣 Full answer (senior)

How I would answer this in an interview

"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 a ValidationProblemDetails by default, so I usually stick with 400 for validation and document it. 401 means 'I don't know who you are', and comes with WWW-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 failed If-Match on an ETag; 429 is rate limiting with a Retry-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."


Success codes

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

Client error pairs

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

Server error codes

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can pick precise status codes and understands how clients and infrastructure act on them.

Green flags

  • Correctly separates 401/403, 404/410, 409/412
  • Uses 201 with Location and 202 for async work
  • Mentions Retry-After on 429/503
  • Explains 502/503/504 as gateway or upstream conditions
  • Ties codes to retries, alerting and ProblemDetails

Red flags

  • Returns 200 for everything with an error flag
  • Uses 500 for validation errors
  • Can't explain the difference between 401 and 403

📚 Learn in depth

1. The classes

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.

2. 201 and Location

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.

3. 202 and asynchronous work

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)

4. 400 vs 422

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.

5. 401 vs 403 in ASP.NET Core

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.

6. 5xx from the edge

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).

7. Error bodies

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.

Try it yourself

  1. Build endpoints returning TypedResults.Created, Accepted, NoContent, Conflict, UnprocessableEntity and inspect them with curl -i.
  2. Add AddProblemDetails() and UseStatusCodePages() and compare the 404 body before and after.
  3. Protect an endpoint with RequireAuthorization("Admin") and call it anonymously and as a non-admin to see 401 vs 403.
  4. In Application Insights, query requests | summarize count() by resultCode and spot any 200s that hide failures.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Returning 200 with {"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.
  • Mistake: Returning 401 when the user is logged in but lacks permission. Why it is wrong: Clients will try to re-authenticate in a loop. Instead: 403 for authenticated-but-forbidden.
  • Mistake: Returning 500 for validation failures. Why it is wrong: It pages on-call, triggers retries and hides that the client must fix the request. Instead: 400 or 422 with field errors.
  • Mistake: 201 without a Location header. Why it is wrong: Clients have to guess or parse the body to find the resource. Instead: TypedResults.Created(uri, dto).
  • Mistake: 429 or 503 without Retry-After. Why it is wrong: Clients retry immediately and make the overload worse. Instead: Send Retry-After in seconds.
  • Mistake: Mixing 400 and 422 for validation across services. Why it is wrong: Every client needs special cases. Instead: Pick one, put it in the API guidelines.
  • Mistake: Returning 403 for another tenant's or customer's resource. Why it is wrong: Confirms the id exists, enabling enumeration. Instead: Return 404.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions error bodies or ProblemDetails Why: Checks how they produce consistent RFC 9457 error responses in ASP.NET Core
    How to answer

    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.

  2. When: Candidate mentions status code classes or idempotency Why: Checks broader HTTP fundamentals for backend engineers
    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.
  3. When: Candidate distinguishes 401 and 403 Why: Checks awareness of resource enumeration and information leakage
    How to answer

    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.

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me