FAQ - Help and questions

How do I validate JSON input in axum and return field errors?

#axum#validation#json#errorspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Deserializing only checks types. Put the rules in a validate method on the input struct, collect every failure into a map of field to message, and return 422 Unprocessable Entity with that map as JSON. Returning all problems at once saves the client repeated round trips.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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));
    }
}
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).

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet