expression

Axum: JSON extraction failures

Malformed syntax, incompatible field types, and an absent JSON media type are distinct failures. This example tests the default response statuses instead of asserting exact framework-generated error messages. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 415 400 422 Common mistake: Depending on exact built-in error text or returning input data in a public error message.

Formal Syntax & Structure

rust syntaxrust
Result<Json<Input>, JsonRejection>

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};    #[derive(serde::Deserialize)]    struct Input { count: u32 }    async fn accept(Json(x): Json<Input>) -> String { x.count.to_string() }    let app = Router::new().route("/count", post(accept));    for (ct, body) in [("text/plain", r#"{"count":3}"#), ("application/json", "{"), ("application/json", r#"{"count":"bad"}"#)] {        let r = app.clone().oneshot(Request::builder().method("POST").uri("/count").header("content-type", ct).body(Body::from(body)).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference