422 responses with field errors

Learn how to return a 422 Unprocessable Entity response with a body that names every field that failed, and how a client reads that body.

A 422 response with field errors tells the client exactly which fields failed and why, all in one body. Instead of a single message like "validation failed", the body carries a map: each field name points to a list of messages for that field. A signup form that sends a short username and an impossible age gets back both problems at once, each attached to the field it belongs to, so the form can show each message next to the right input box.

{"error": "validation failed", "fields": {"username": ["username must be at least 3 characters long"], "age": ["age must be between 0 and 150"]}}

Where This Fits

The page before this one collected every failure into one flat message, with the problems joined by semicolons. That message is readable, but a client program cannot tell which part of it belongs to which field without parsing words. This page gives each failure a field name of its own, so the client never has to parse a sentence. Think of it like the difference between a teacher writing "two mistakes on the test" at the top of the page and a teacher circling each mistake next to the question it belongs to.

The Smallest Working Version

Start with one route, one field, and one rule: a username must be present. Create a project with these files. The error type is the shared one from the project, and this page adds one helper function to it for the field-error body.

# Cargo.toml
[package]
name = "validation-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
// src/errors.rs
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use std::collections::HashMap;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
    Unauthorized,
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => {
                (StatusCode::UNPROCESSABLE_ENTITY, message)
            }
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

pub fn field_errors_response(fields: HashMap<String, Vec<String>>) -> Response {
    (
        StatusCode::UNPROCESSABLE_ENTITY,
        Json(json!({ "error": "validation failed", "fields": fields })),
    )
        .into_response()
}

pub fn add_error(errors: &mut HashMap<String, Vec<String>>, field: &str, message: &str) {
    errors
        .entry(field.to_string())
        .or_default()
        .push(message.to_string());
}
// src/lib.rs
use axum::{extract::Json, http::StatusCode, response::Response, routing::post, Router};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;

use crate::errors::{add_error, field_errors_response};

#[derive(Deserialize)]
pub struct SignupInput {
    pub username: Option<String>,
}

pub fn validate_signup(input: &SignupInput) -> HashMap<String, Vec<String>> {
    let mut errors: HashMap<String, Vec<String>> = HashMap::new();
    match &input.username {
        None => add_error(&mut errors, "username", "username is required"),
        Some(name) if name.trim().is_empty() => {
            add_error(&mut errors, "username", "username must not be empty")
        }
        Some(_) => {}
    }
    errors
}

pub async fn create_account(Json(input): Json<SignupInput>) -> Response {
    let errors = validate_signup(&input);
    if !errors.is_empty() {
        return field_errors_response(errors);
    }
    (
        StatusCode::CREATED,
        Json(json!({ "message": "account created" })),
    )
        .into_response()
}

pub fn app() -> Router {
    Router::new().route("/accounts", post(create_account))
}
// src/main.rs
use validation_demo::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}

Run the server with cargo run, then send a request with no username:

curl -X POST http://127.0.0.1:3000/accounts -H "content-type: application/json" -d '{}'

The server answers with status 422 and this body:

{"error": "validation failed", "fields": {"username": ["username is required"]}}

Send a username with real text:

curl -X POST http://127.0.0.1:3000/accounts -H "content-type: application/json" -d '{"username": "ada"}'

The server answers with status 201 and this body:

{"message": "account created"}

The two top-level keys in the error body each do one job. "error" carries the short human summary, always the words "validation failed". "fields" carries the map, with one entry per failing field.

The Smallest Version Works:

If an empty body returns 422 with the fields map naming username, and a good username returns 201, the field-error response is wired up correctly. Everything later on this page adds more fields to the same map.

How the Field-Error Body Is Built, Piece by Piece

Three pieces of Rust build the body, and each one is worth understanding because each one answers a question a beginner will ask when the body does not look the way they expected.

The map holds one entry per failing field

let mut errors: HashMap<String, Vec<String>> = HashMap::new();

A HashMap is a map from keys to values: give it a key, and it gives back the value stored under that key. Here the key is the field name, a String like "username", and the value is a Vec<String>, a list of messages for that field. A field that passes validation never gets an entry in the map. A field that fails gets exactly one entry, no matter how many messages it has. That is what makes the body easy to read: one entry per field, and the client can look a field up by name.

add_error appends a message to a field

pub fn add_error(errors: &mut HashMap<String, Vec<String>>, field: &str, message: &str) {
    errors
        .entry(field.to_string())
        .or_default()
        .push(message.to_string());
}

.entry(field.to_string()) finds the entry for the field name, or prepares to create one if it is not there yet. .or_default() creates an empty list when the field has no entry, and returns the existing list when it does. .push(message.to_string()) adds the new message to the end of that list. The first message for a field creates the entry and the list in one step. The second message for the same field finds the existing list and appends to it. The caller never has to check whether the field already has an entry, which is the whole reason this helper exists.

The &mut on the first argument means the function borrows the map and is allowed to change it. The caller keeps owning the map, and the helper only adds to it. Every check in the validate function calls this same helper, so every message lands in the same map.

json! turns the map into a JSON body

Json(json!({ "error": "validation failed", "fields": fields }))

json! is a macro from the serde_json crate that builds a JSON value from Rust values, using syntax that looks like the JSON itself. The "fields" key takes the HashMap directly, and serde_json turns each map entry into a JSON object key with a list of strings as its value. The Json wrapper then sets the content-type header to application/json and writes the value as the response body. Building the body this way means the server never assembles JSON by hand, so a quote or a backslash inside a message cannot break the output.

The tuple (StatusCode::UNPROCESSABLE_ENTITY, Json(...)) pairs the status with the body, and .into_response() turns the pair into a full HTTP response. StatusCode::UNPROCESSABLE_ENTITY is the name of status 422 in the http crate, which Axum re-exports. Writing the name instead of the number 422 keeps the code readable, and the compiler checks the name exists, which a bare number would not.

Field Order in the Body Is Not Guaranteed:

A HashMap does not keep its entries in insertion order, so the fields in the body can appear in any order. One run might list age before username, and the next might list them the other way round. Clients must look fields up by name, never by position. Tests on this page parse the body as JSON and read fields by name for the same reason.

The Concept Behind the Fields Map

The fields map is a contract between the server and the client about how validation failures are reported. The contract has three parts, and each part is fixed so both sides can rely on it.

First, the status is always 422. A client that sees 422 knows the request was understood and the data failed the rules, without reading the body at all.

Second, the "error" key is always the string "validation failed". It never names a field and never changes with the request. A log viewer or a generic error display can show it as-is.

Third, the "fields" key is a map from field name to a list of messages. The list is always a list, even when a field has only one message. That uniformity matters: a client reads fields["username"] and always gets a list it can loop over, instead of sometimes getting a string and sometimes getting a list. A field with two problems gets two messages in its list, in the order the checks ran.

Beginners should think of the body as an envelope with a label and a set of marked pages. The label says "validation failed". Each marked page is a field, and the marks on it are the messages.

Why 422 and Not 400

Status 400 and status 422 both mean the request failed, but they mean different kinds of failure, and picking the wrong one sends the client the wrong message about what to fix.

SituationStatusMeaning
The JSON text is broken, like {"username": with no closing brace400 Bad RequestThe server could not read the request at all
The JSON parses but a field has the wrong type, like "age": "old"422 Unprocessable EntityThe server read the request but the content does not fit
The JSON parses and the types fit, but a value breaks a rule, like an age of 200422 Unprocessable EntityThe server read the request but the content fails the rules

Status 400 means the request was malformed: broken syntax, a missing content type, a body the server could not parse. There is nothing for the client to fix except the shape of the request itself. Status 422 means the request was well formed and the server understood it, but the content fails the rules. The client fixes it by changing a value, not by fixing syntax.

A request with broken JSON sent to the route on this page returns 400, which was checked by running the server and sending {"username": as the body. A request with a missing username returns 422. The two statuses side by side are the proof that the line between them is real and that the server draws it in the same place for its own checks as Axum draws it for the extractor.

Do Not Use 400 for a Failed Rule:

A 400 for a validation failure is the most common status mistake in hand-written validation. It compiles, it runs, and the client still sees an error, so it survives unnoticed. The damage is quiet: automated clients that retry 400s as syntax errors, and developers who read the status and look in the wrong place. Keep 400 for requests the server cannot read, and 422 for requests it read and rejected.

A Richer Complete Example

A real signup form has more than one field, and the same map collects all of them. This example grows the smallest version into a full signup with a username, an age, and an email, using the presence checks and the range and length checks from the earlier pages in this group.

// src/lib.rs
use axum::{extract::Json, http::StatusCode, response::Response, routing::post, Router};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;

use crate::errors::{add_error, field_errors_response};

#[derive(Deserialize)]
pub struct SignupInput {
    pub username: Option<String>,
    pub age: Option<i32>,
    pub email: Option<String>,
}

pub fn validate_signup(input: &SignupInput) -> HashMap<String, Vec<String>> {
    let mut errors: HashMap<String, Vec<String>> = HashMap::new();
    match &input.username {
        None => add_error(&mut errors, "username", "username is required"),
        Some(name) if name.trim().is_empty() => {
            add_error(&mut errors, "username", "username must not be empty")
        }
        Some(name) => {
            let length = name.trim().chars().count();
            if length < 3 {
                add_error(
                    &mut errors,
                    "username",
                    "username must be at least 3 characters long",
                );
            }
            if length > 30 {
                add_error(
                    &mut errors,
                    "username",
                    "username must be at most 30 characters long",
                );
            }
        }
    }
    match input.age {
        None => add_error(&mut errors, "age", "age is required"),
        Some(age) if !(0..=150).contains(&age) => {
            add_error(&mut errors, "age", "age must be between 0 and 150")
        }
        Some(_) => {}
    }
    match &input.email {
        None => add_error(&mut errors, "email", "email is required"),
        Some(email) if email.trim().is_empty() => {
            add_error(&mut errors, "email", "email must not be empty")
        }
        Some(email) if !email.contains('@') => {
            add_error(&mut errors, "email", "email must contain @")
        }
        Some(_) => {}
    }
    errors
}

pub async fn create_account(Json(input): Json<SignupInput>) -> Response {
    let errors = validate_signup(&input);
    if !errors.is_empty() {
        return field_errors_response(errors);
    }
    (
        StatusCode::CREATED,
        Json(json!({ "message": "account created" })),
    )
        .into_response()
}

pub fn app() -> Router {
    Router::new().route("/accounts", post(create_account))
}

The age field is an Option<i32> here, not a plain i32, for the same reason the username is an Option<String>: a missing age should land in the fields map with the message "age is required", not in the extractor's own rejection. The match on input.age has three arms: absent, present but outside the range, and present and inside. The guard Some(age) if !(0..=150).contains(&age) is the range check from the previous page, moved inside the match so it only runs when a value actually arrived.

The email check adds one more arm shape: a present email that has no @ character gets the message "email must contain @". That is a shape check, not a full check that the address is real. It catches the most common typo, an address typed without its @.

Send a request that fails on every field:

curl -X POST http://127.0.0.1:3000/accounts -H "content-type: application/json" -d '{"username": "ad", "age": 200}'

The server answers with status 422 and this body:

{"error": "validation failed", "fields": {"age": ["age must be between 0 and 150"], "email": ["email is required"], "username": ["username must be at least 3 characters long"]}}

All three failing fields appear, each with its own list. Send an empty body:

curl -X POST http://127.0.0.1:3000/accounts -H "content-type: application/json" -d '{}'

The server answers with status 422 and this body:

{"error": "validation failed", "fields": {"age": ["age is required"], "email": ["email is required"], "username": ["username is required"]}}

Every field is required, so an empty body fails on all three at once, and the client learns that in a single response instead of three round trips.

One Field With Two Messages

A field can fail two checks at once, and the list is what makes that visible. An email that is present but has no @ fails the shape check, and a username that is present but too short fails the length check. Neither of those is a second field, so neither gets a second map entry. The messages stack up inside the one list for that field.

curl -X POST http://127.0.0.1:3000/accounts -H "content-type: application/json" -d '{"username": "ada", "age": 30, "email": "not-an-email"}'

The server answers with status 422 and this body:

{"error": "validation failed", "fields": {"email": ["email must contain @"]}}

The map has one entry, because only one field failed. A form reading this body puts the message next to the email input and leaves the other inputs alone. That is the behaviour the whole shape exists for: the client can mark exactly the fields that failed, and no others.

A username that is both too short and, in a stricter form, missing a required character would get two messages in its list, in the order the checks ran. The client loops over the list and shows both under the same input. Nothing in the shape changes when a field gains a second message, which is why the value is a list and not a single string. A single string would force the server to glue two messages together and the client to split them apart again.

A Passing Field Has No Entry:

The map only contains fields that failed. A client checks whether a field is in the map to decide whether to mark it. Testing fields["username"] for existence is the whole test: present means failed, absent means passed. There is no entry that says "this field is fine".

How a Client Reads the Body

The body is only useful if the client can read it, so this section shows the reading from the client side. The body is ordinary JSON, and any JSON parser can handle it. The client reads the status first, then the "error" headline, then the "fields" map.

With curl, the response is already visible: the status line says 422 Unprocessable Entity, and the body prints the map. A browser form using fetch reads it like this:

const response = await fetch("/accounts", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ username: "ad", age: 200 }),
});
if (response.status === 422) {
    const body = await response.json();
    for (const [field, messages] of Object.entries(body.fields)) {
        console.log(field, messages[0]);
    }
}

response.json() parses the body into a JavaScript object. Object.entries(body.fields) walks each field name and its list of messages, one pair at a time. A real form would take each pair and write the first message next to the input with that name, instead of logging it. The loop works no matter how many fields failed, and it works when only one failed, because the shape is the same in both cases.

A Rust client reads it the same way, with serde_json::Value, a type that holds any JSON value without a fixed struct:

let value: serde_json::Value = serde_json::from_str(&body).unwrap();
let username_errors = &value["fields"]["username"];
assert_eq!(username_errors[0], "username must be at least 3 characters long");

Indexing a Value with ["fields"] and then ["username"] walks the map by key, and [0] takes the first message in the list. The tests at the end of this page read the body exactly this way, which is why they keep passing even when the field order in the body changes: they look each field up by name.

How a Request Flows Through the Map

Client sends JSON body
        |
        v
Json extractor turns the body into SignupInput
        |
        v
Handler calls validate_signup
        |
        v
Username tested ------> add_error on failure
Age tested -----------> add_error on failure
Email tested ---------> add_error on failure
        |
        v
Errors map empty?
        |
   yes /       \ no
      /         \
     v           v
201 created   422 {"error": "validation failed",
                   "fields": { ... }}

The diagram shows the same collecting shape as the previous page, with one change at the end: the failures gather in a map keyed by field name instead of a flat list. The handler still waits until every test has run, and only then decides. The decision is the same test, errors.is_empty(), applied to a map instead of a list.

Testing It

Tests for the field-error body send requests straight to the router without starting a server. The tower crate provides oneshot, a method that runs one request through the router and returns the response. Add it as a dev-dependency, which is a dependency used only by tests:

# Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/account_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use tower::ServiceExt;
use validation_demo::app;

async fn post_account(body: &str) -> (StatusCode, String) {
    let response = app()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/accounts")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    let status = response.status();
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    (status, String::from_utf8(bytes.to_vec()).unwrap())
}

#[tokio::test]
async fn multiple_fields_are_listed_together() {
    let (status, body) =
        post_account(r#"{"username": "ad", "age": 200}"#).await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    let value: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(value["error"], "validation failed");
    assert_eq!(
        value["fields"]["username"][0],
        "username must be at least 3 characters long"
    );
    assert_eq!(value["fields"]["age"][0], "age must be between 0 and 150");
    assert_eq!(value["fields"]["email"][0], "email is required");
}

#[tokio::test]
async fn empty_body_lists_every_field() {
    let (status, body) = post_account(r#"{}"#).await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    let value: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(value["error"], "validation failed");
    assert_eq!(value["fields"]["username"][0], "username is required");
    assert_eq!(value["fields"]["age"][0], "age is required");
    assert_eq!(value["fields"]["email"][0], "email is required");
}

#[tokio::test]
async fn one_field_with_one_message() {
    let (status, body) = post_account(
        r#"{"username": "ada", "age": 30, "email": "not-an-email"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    let value: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(value["fields"]["email"][0], "email must contain @");
}

#[tokio::test]
async fn valid_account_returns_201() {
    let (status, body) = post_account(
        r#"{"username": "ada", "age": 36, "email": "ada@example.com"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    assert_eq!(body, r#"{"message":"account created"}"#);
}

Each test parses the body with serde_json::from_str and reads fields by name, so none of them depends on the order the map prints in. Run them with cargo test. All four pass against the code on this page.

What the Tests Prove:

Four tests, four behaviours: several fields failing together, every field failing at once, one field failing alone, and a valid request. If all four pass, the map is complete when it should be, narrow when it should be, and absent when the request is good.

Common Beginner Mistakes

Returning the plain ValidationError for field failures

// Wrong - the client gets one message and loses the field names
let errors = validate_signup(&input);
if !errors.is_empty() {
    return Err(AppError::ValidationError("validation failed".to_string()));
}

The map was built and then thrown away. The client gets the headline and nothing else, and the form cannot tell which input to mark. The fix is the line from this page: return field_errors_response(errors) from a handler that returns a Response, so the map reaches the body. The plain ValidationError still has its place, for a single failure that belongs to no field in particular. A failure that belongs to a field belongs in the map.

The Handler Return Type Has to Change:

A handler that returns Result<Json<User>, AppError> cannot return the field-error body, because that body is not an AppError. The handler on this page returns a bare Response instead, which can hold either the 422 field-error body or the 201 success body. Forgetting to change the return type is the compile error that points at this mistake.

Using a list instead of a map

// Wrong - the client cannot tell which message belongs to which field
Json(json!({ "error": "validation failed", "fields": ["username is required"] }))

A list of messages without field names is the flat joined message from the previous page wearing a new key. The client still has to parse words to find the field. The fix is the map: HashMap<String, Vec<String>>, one entry per field, looked up by name.

Giving each field a single string instead of a list

// Wrong - a field with two problems has nowhere to put the second one
Json(json!({ "error": "validation failed", "fields": { "email": "email must contain @" } }))

A single string per field works until a field fails twice, and then the server has to glue two messages into one string or drop one of them. The list costs nothing when there is one message, and it is the only shape that holds two. Keep the value a Vec<String> from the start, even when every field on the page has only one message so far.

Building the JSON by hand with format!

// Wrong - a quote inside a message breaks the body
let body = format!("{{\"error\": \"validation failed\", \"fields\": {}}}", fields_text);

Hand-built JSON has no escaping. A message containing a quote, a backslash, or a newline produces a body that is not valid JSON, and the client fails to parse the very response meant to help it. The fix is json!, which escapes every value it is given. Never assemble a JSON body from string pieces when serde_json is already a dependency.

Using 400 for a field failure

// Wrong - 400 says the request could not be read
(StatusCode::BAD_REQUEST, Json(json!({ "error": "validation failed", "fields": fields })))

The body is right and the status is wrong. A 400 tells the client the request was malformed, which sends it looking for a syntax problem. The field checks only run on requests that parsed cleanly, so the status for their failure is 422. field_errors_response hard-codes 422 for exactly this reason: the status is part of the contract, not a choice the handler makes per request.

Final Complete Example

Here is everything from the page put together: the shared error type with the field-error helper, the signup input and validate function, the handler, the server entry point, and the tests.

// src/errors.rs
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use std::collections::HashMap;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
    Unauthorized,
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => {
                (StatusCode::UNPROCESSABLE_ENTITY, message)
            }
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

pub fn field_errors_response(fields: HashMap<String, Vec<String>>) -> Response {
    (
        StatusCode::UNPROCESSABLE_ENTITY,
        Json(json!({ "error": "validation failed", "fields": fields })),
    )
        .into_response()
}

pub fn add_error(errors: &mut HashMap<String, Vec<String>>, field: &str, message: &str) {
    errors
        .entry(field.to_string())
        .or_default()
        .push(message.to_string());
}
// src/lib.rs
use axum::{extract::Json, http::StatusCode, response::Response, routing::post, Router};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;

use crate::errors::{add_error, field_errors_response};

#[derive(Deserialize)]
pub struct SignupInput {
    pub username: Option<String>,
    pub age: Option<i32>,
    pub email: Option<String>,
}

pub fn validate_signup(input: &SignupInput) -> HashMap<String, Vec<String>> {
    let mut errors: HashMap<String, Vec<String>> = HashMap::new();
    match &input.username {
        None => add_error(&mut errors, "username", "username is required"),
        Some(name) if name.trim().is_empty() => {
            add_error(&mut errors, "username", "username must not be empty")
        }
        Some(name) => {
            let length = name.trim().chars().count();
            if length < 3 {
                add_error(
                    &mut errors,
                    "username",
                    "username must be at least 3 characters long",
                );
            }
            if length > 30 {
                add_error(
                    &mut errors,
                    "username",
                    "username must be at most 30 characters long",
                );
            }
        }
    }
    match input.age {
        None => add_error(&mut errors, "age", "age is required"),
        Some(age) if !(0..=150).contains(&age) => {
            add_error(&mut errors, "age", "age must be between 0 and 150")
        }
        Some(_) => {}
    }
    match &input.email {
        None => add_error(&mut errors, "email", "email is required"),
        Some(email) if email.trim().is_empty() => {
            add_error(&mut errors, "email", "email must not be empty")
        }
        Some(email) if !email.contains('@') => {
            add_error(&mut errors, "email", "email must contain @")
        }
        Some(_) => {}
    }
    errors
}

pub async fn create_account(Json(input): Json<SignupInput>) -> Response {
    let errors = validate_signup(&input);
    if !errors.is_empty() {
        return field_errors_response(errors);
    }
    (
        StatusCode::CREATED,
        Json(json!({ "message": "account created" })),
    )
        .into_response()
}

pub fn app() -> Router {
    Router::new().route("/accounts", post(create_account))
}
// src/main.rs
use validation_demo::app;

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app()).await.unwrap();
}
# Cargo.toml
[package]
name = "validation-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the checks with:

cargo test

Run the server with:

cargo run

Try the failing requests from the testing section, the empty body, and the valid request, and compare the responses with the ones shown there.

Summary

The field-error body turns a validation failure from a sentence into a structure. The status stays 422, because the request was readable and the content failed the rules. The "error" key stays a fixed headline, because a log reader should not have to parse it. The "fields" map does the real work: one entry per failing field, one list of messages per entry, looked up by name.

The decision the three pages in this group add up to is a simple one. A single failure with no field attached gets the plain message. A failure that belongs to a field gets the map. A request that fails on several fields gets the whole map in one response, so the client fixes everything in one round.