expression
Axum: field-level validation errors
An API can return field-specific validation details so the caller knows which value to correct. Keep error codes stable and avoid echoing sensitive submitted values. This example collects two failures in an explicit order. In-memory standalone Cargo example. Expected stdout (not executed): 422 name quantity Common mistake: Including the full submitted body in the error message.
Formal Syntax & Structure
rust syntaxrust
(StatusCode::UNPROCESSABLE_ENTITY, Json(error))Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::{Json, routing::post, response::{IntoResponse, Response}}; #[derive(serde::Deserialize)] struct Input { name: String, quantity: u16 } async fn check(Json(x): Json<Input>) -> Response { let mut fields = Vec::new(); if x.name.trim().is_empty() { fields.push("name"); } if x.quantity == 0 { fields.push("quantity"); } if fields.is_empty() { return StatusCode::NO_CONTENT.into_response(); } (StatusCode::UNPROCESSABLE_ENTITY, Json(serde_json::json!({"code":"invalid_input", "fields":fields}))).into_response() } let r = Router::new().route("/", post(check)).oneshot(Request::builder().method("POST").uri("/").header("content-type", "application/json").body(Body::from(r#"{"name":"", "quantity":0}"#)).unwrap()).await.unwrap(); println!("{}", r.status().as_u16()); let v: serde_json::Value = serde_json::from_slice(&to_bytes(r.into_body(), 256).await.unwrap()).unwrap(); for field in v["fields"].as_array().unwrap() { println!("{}", field.as_str().unwrap()); }}