Answer#
Serde guarantees that age is a number between 0 and 255 (for a u8), not that it is a sensible age. Rules about content belong in code you write: a method on the input type that returns every problem, and a handler that turns the problems into a 422 response.
use axum::{body::{to_bytes, Body}, http::{header, Request, StatusCode}, routing::post, Json, Router};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use tower::ServiceExt;
#[derive(Deserialize)]
struct SignUp { email: String, age: u8 }
#[derive(Serialize)]
struct Problems { errors: BTreeMap<&'static str, &'static str> }
impl SignUp {
fn validate(&self) -> Result<(), Problems> {
let mut errors = BTreeMap::new();
if !self.email.contains('@') || self.email.len() > 254 { errors.insert("email", "must be an e-mail address"); }
if self.age < 13 { errors.insert("age", "must be 13 or older"); }
if errors.is_empty() { Ok(()) } else { Err(Problems { errors }) }
}
}
async fn sign_up(Json(s): Json<SignUp>) -> Result<StatusCode, (StatusCode, Json<Problems>)> {
s.validate().map_err(|p| (StatusCode::UNPROCESSABLE_ENTITY, Json(p)))?;
Ok(StatusCode::CREATED)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/signup", post(sign_up));
for body in [r#"{"email":"[email protected]","age":30}"#, r#"{"email":"nope","age":9}"#] {
let req = Request::post("/signup").header(header::CONTENT_TYPE, "application/json").body(Body::from(body)).unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let status = res.status().as_u16();
let text = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{status} {}", String::from_utf8_lossy(&text));
}
}201
422 {"errors":{"age":"must be 13 or older","email":"must be an e-mail address"}}A valid body gave 201 with no content. The invalid body produced both messages at once, in a stable order because the map is a BTreeMap.
Common mistakes#
- Stopping at the first error. A client that fixes one field and resubmits to find the next learns the rules slowly.
- Checking only on the client side. Anyone can call the endpoint directly, so the server must check too.
- Echoing back the rejected value in the message when it may be private (a password, a token).
Related questions#
400 or 422 for failed validation?#
This thread uses 422 for input that parses but breaks a rule, and axum itself uses 400 for broken JSON and 422 for a shape mismatch (see the thread on 415, 400 and 422). Choose one convention and document it for your clients.
Is there a crate for this?#
Validation crates exist; this thread shows the plain-Rust version and does not compare crates.
Sources#
- MDN, 422 Unprocessable Content: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 (read 2026-12-05)
- axum,
Json: https://docs.rs/axum/0.8.9/axum/struct.Json.html (read 2026-12-05)