400 or 422?

A signup form sends {"email": "not-an-email"}. One endpoint of your API answers 400. Another, written by a colleague a year later, answers 422 for the same mistake. A third answers 400 with a bare string where the others send JSON. Someone opens a pull request to tidy this up, and the review turns into a debate where every comment cites an RFC.

Both sides can cite one, which is why the debate never ends.

This article gives you a policy you can adopt in an afternoon: three status codes, one question for each, and one place in the code that applies them. Examples use ASP.NET Core minimal APIs, but the reasoning holds for any stack.

The version everyone writes first

Nobody decides, so every endpoint decides for itself:

// Endpoint 1: the framework default
return Results.ValidationProblem(result.ToDictionary());              // 400, Problem Details

// Endpoint 2: written after reading about 422
return Results.UnprocessableEntity(new { error = "Invalid email" });  // 422, custom JSON

// Endpoint 3: written in a hurry
return Results.BadRequest("Email already registered");                // 400, a bare string

Each line is reasonable on its own. Each one passed review, because the reviewer was looking at one endpoint.

Why it fails

Look at the API from the client's side:

Endpoint What went wrong Status Body
POST /users Email has no @ 400 Problem Details with errors
POST /invites Email has no @ 422 { "error": "..." }
POST /teams Name already taken 400 "Name already taken"

The client can't write one error handler. It needs a branch per endpoint, and each branch is a guess that breaks when the endpoint changes. Tacitus wrote of the late Roman Republic: corruptissima re publica plurimae leges, the more corrupt the state, the more numerous its laws. A client with a special case for every endpoint is talking to an API that never decided.

The standards won't decide for you either:

A mistyped email fits both descriptions. Ecosystems picked differently: the GitHub REST API, Rails and FastAPI answer validation errors with 422. ASP.NET Core answers them with 400, in every place it validates for you: [ApiController] model validation, Results.ValidationProblem, and the built-in minimal API validation in .NET 10.

So the question "which one is correct?" has no answer. The useful question is different: what can the client do with the code?

The fix: three codes, three questions

A status code earns its place only if the client reacts differently to it. For a refused write, there are three different reactions, so there are three codes. Ask the questions in order and stop at the first yes:

  1. Could someone holding only the API documentation see that this request is wrong? Then it's a 400. Broken JSON, a missing field, an email without @, a name over the maximum length.
  2. Is the request fine, but the resource is already in a state that rules it out? Then it's a 409. The email is already registered, the order has already shipped, the record changed since the client read it.
  3. Is the request fine, and a business rule refuses it? Then it's a 422. Signups are closed for this domain, the transfer is above the daily limit.

Three questions asked in order: wrong by the API documentation alone gives 400, ruled out by the current state gives 409, refused by a business rule gives 422.

Code Who is "wrong" What the client does
400 The request, by the contract Fix the request. Show the field errors next to the fields.
409 Nobody; the state got there first Reload the current state and show it.
422 Nobody; the business says no Show the rule's message.

For both 409 and 422, retrying the request unchanged won't help while the relevant state stays the same. Whether it helps later depends on the specific problem: an email stays taken, a daily limit resets at midnight. That level of detail belongs to the type described below, not to the status code.

Ulpian summed up Roman law in three precepts, and the third is the one that applies here: suum cuique tribuere, give each his own. Each kind of failure gets its own code, and no failure gets two.

Why 400 for validation, on .NET

Choosing 422 for validation errors is a legitimate policy, and several widely used frameworks choose it. On ASP.NET Core it means overriding the default in every place the framework validates, and the one you miss brings the mix back. Staying with 400 costs nothing and matches what .NET clients and tools already expect.

If your API already answers validation errors with 422 everywhere, keep it. Consistency is the goal; the number is secondary.

The border between 409 and 422

This border is not sharp. A seat limit on a plan is a business rule, but it's also state: delete a user and the same request succeeds. The Greeks had a paradox for this, attributed to Eubulides of Miletus: one grain of sand is not a heap, adding one grain never turns a non-heap into a heap, and yet heaps exist. You won't find the exact grain where a conflict becomes a refusal.

A rule of thumb gets most cases right. If the honest message starts with "it already…" (exists, shipped, changed), use 409. If it starts with "you may not…", use 422. For the rest, decide once per error, write the decision down, and move on. The next two sections keep the cost of a borderline decision small.

One catalogue applies the policy

The policy lives in one file. Endpoints pick an error; they never pick a number:

// The whole status code policy: three kinds of failure, three codes.
public enum ErrorKind
{
    Invalid = 400,  // wrong according to the API contract: fix the request
    Conflict = 409, // fine on its own, but the resource's current state says no
    Refused = 422,  // fine on its own, but a business rule says no
}

// One entry in the error catalogue. Code is the stable part clients may branch on.
public sealed record Error(string Code, ErrorKind Kind, string Title)
{
    private const string BaseUri = "https://errors.acme.example/";

    public string Type => BaseUri + Code;

    public IResult ToProblem(string? detail = null) =>
        Results.Problem(type: Type, title: Title, detail: detail, statusCode: (int)Kind);
}

public static class Errors
{
    public static readonly Error ValidationFailed =
        new("validation-failed", ErrorKind.Invalid, "One or more fields are invalid");

    public static readonly Error EmailTaken =
        new("email-taken", ErrorKind.Conflict, "Email already registered");

    public static readonly Error SignupDomainClosed =
        new("signup-domain-closed", ErrorKind.Refused, "Signups are closed for this domain");

    // Field errors keep the "errors" member that ASP.NET Core clients already know.
    public static IResult Validation(IDictionary<string, string[]> errors) =>
        Results.ValidationProblem(
            errors,
            type: ValidationFailed.Type,
            title: ValidationFailed.Title,
            statusCode: (int)ValidationFailed.Kind);
}

The signup endpoint now asks the three questions, the third before the second:

var result = await validator.ValidateAsync(signup, ct);
if (!result.IsValid)
{
    return Errors.Validation(result.ToDictionary()); // 400: the contract says this request is wrong
}

var email = Email.Normalize(signup.Email);
var domain = Email.DomainOf(email);
if (closedDomains.Contains(domain))
{
    // 422: a valid request that a business rule refuses
    return Errors.SignupDomainClosed.ToProblem(
        $"Accounts for {domain} are created by the organisation's administrator.");
}

db.Users.Add(new User { Email = email });
try
{
    await db.SaveChangesAsync(ct);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException
{
    SqlState: PostgresErrorCodes.UniqueViolation,
    ConstraintName: AppDb.UsersEmailIndex
})
{
    // 409: a valid request that the current state of the table refuses
    return Errors.EmailTaken.ToProblem("An account with this email already exists.");
}

The questions classify a failure; they don't fix the order of the checks. A signup for a closed domain, with an address that is already registered, fails both ways, and the API has to decide which answer it gives. This one checks the domain rule first: it needs no database round trip, and the refusal holds whether or not the address exists. Whatever precedence you choose, write it down next to the catalogue.

The domain rule is also only as good as the validation before it. FluentValidation's EmailAddress() deliberately checks little more than the presence of an @, so dana@ corp.example passes it, and its "domain" starts with a space and misses the closed list. The sample's validator therefore defines the syntax this API accepts (one @, no whitespace, a dot in the domain) before any rule reads the domain.

A reviewer who disagrees with a status code now has one line to change, in the catalogue, and the change applies everywhere that error is returned.

The type is the contract

Every response is Problem Details (RFC 9457), and every error has its own type. These are the sample's real responses, with the trace ID removed:

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json

{"type":"https://errors.acme.example/validation-failed","title":"One or more fields are invalid","status":400,"errors":{"Email":["'Email' must look like name@example.com, with no spaces."]}}
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json

{"type":"https://errors.acme.example/signup-domain-closed","title":"Signups are closed for this domain","status":422,"detail":"Accounts for corp.example are created by the organisation's administrator."}
HTTP/1.1 409 Conflict
Content-Type: application/problem+json

{"type":"https://errors.acme.example/email-taken","title":"Email already registered","status":409,"detail":"An account with this email already exists."}

The two parts do different jobs:

That limits the cost of a borderline 409-or-422 decision. If you later move the seat limit from one to the other, clients that dispatch only on type keep their handling. Everything that reads the status code can still be affected, so the change needs a compatibility review, as the last section says.

Two details from the output above:

Failures your code never sees

Broken JSON never reaches the endpoint; the framework rejects it during binding. A few lines give those failures the same media type as your own errors:

builder.Services.AddProblemDetails();
// ...
app.UseExceptionHandler(new ExceptionHandlerOptions
{
    // Keep the status a bad request carries instead of reporting it as a 500.
    StatusCodeSelector = ex => ex is BadHttpRequestException bad
        ? bad.StatusCode
        : StatusCodes.Status500InternalServerError,
});
app.UseStatusCodePages();

The selector matters in Development. There, minimal APIs throw a BadHttpRequestException for a body they can't bind, and a plain UseExceptionHandler() reports it as a 500. In Production the framework answers 400 without throwing. With the selector, broken JSON is a 400 in both:

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json

{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Bad Request","status":400}

The same middleware covers unknown routes (404) and unhandled exceptions (500). It gives otherwise empty error responses a Problem Details body when the client accepts JSON. A client that asks only for text/html gets a plain-text line, and failures that happen outside the application, in a proxy or a load balancer, aren't covered at all.

What stays out of the policy

The rule

  1. 400 when the contract says the request is wrong. It's the ASP.NET Core default; don't fight it.
  2. 409 when the state says no, 422 when a business rule says no. Decide once per error, in a catalogue, never per endpoint.
  3. Give every error a stable type. Clients branch on the type; the status code is for everything in between.

Tradition has it that Rome's first written law, the Twelve Tables, was set up on the Rostra so that nobody had to guess what the rules were. A status code policy needs the same treatment: short, written down, and in one place where every endpoint can see it. Which number you wrote matters less than the fact that you wrote one.

Run it yourself

The companion sample is a minimal ASP.NET Core API with one endpoint, POST /users, and the catalogue above. The 409 comes from a unique index, as described in A database constraint beats an async validator. It runs entirely in Docker, next to PostgreSQL:

docker compose up -d --build

Then send one request per question:

curl -i -X POST http://localhost:5081/users -H "Content-Type: application/json" -d '{"email":"not-an-email"}'
curl -i -X POST http://localhost:5081/users -H "Content-Type: application/json" -d '{"email":"dana@corp.example"}'
curl -i -X POST http://localhost:5081/users -H "Content-Type: application/json" -d '{"email":"dana@acme.example"}'

Run the last one twice: the first call returns 201, the second 409. The closed domains are a setting, Signup:ClosedDomains in appsettings.json.

Further reading


This article is part of Justified Complexity: Building Backends One Decision at a Time.

Updated 2026-11-11: malformed JSON returned 500 when the sample ran in Development, and the exception handler now keeps the 400; the sample validates email syntax more strictly before the domain rule; the article now states that the 422 check runs before the 409 one, qualifies the retry guidance and the claim about changing a status code, and dates the broad definition of 400 to RFC 7231. The classical references now link to their sources; the Twelve Tables are said to have been set up on the Rostra, as Diodorus reports, where the article used to say "posted in the Forum".