Put Axum `Json` last in the handler
Axum extractors run from left to right in function-argument order. A body-consuming extractor such as Json<T can read the request body only once, so it must be the final argument. This example uses Axum 0.8.9.
Axum extractors run from left to right in function-argument order. A body-consuming extractor such as Json<T> can read the request body only once, so it must be the final argument. This example uses Axum 0.8.9.
Read a path value and JSON body
Path<u64> reads the project ID from the route. Json<CreateProject> deserializes the body. Since only the latter consumes the body, it goes last.
[dependencies]
axum = "0.8.9"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }Dependencies
use axum::{
extract::Path,
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateProject {
name: String,
}
#[derive(Serialize)]
struct ProjectReply {
id: u64,
name: String,
}
async fn create_project(
Path(project_id): Path<u64>,
Json(input): Json<CreateProject>,
) -> (StatusCode, Json<ProjectReply>) {
(
StatusCode::CREATED,
Json(ProjectReply {
id: project_id,
name: input.name,
}),
)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/projects/{id}", post(create_project));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.expect("bind listener");
axum::serve(listener, app).await.expect("serve app");
}Why order matters
The request body is a one-use asynchronous stream. Only one extractor may consume it, and it must be last; Path, Query, State, and headers can precede it. A String and Json cannot both consume the same body. By default, a failed extractor returns a rejection response without calling the handler. To handle JSON errors in one handler, accept Result<Json<T>, JsonRejection>; that body-consuming argument still belongs last.
Local verification
With Rust and Cargo installed, run cargo run, then POST {"name":"Notes"} to http://127.0.0.1:3000/projects/42 with Content-Type: application/json. Expected: 201 and {"id":42,"name":"Notes"}. Invalid JSON or a non-numeric ID should be rejected before the handler. This example was not compiled or run.
If compilation fails, keep the body-consuming extractor last and enable Serde derive. For a rejection, inspect the route, JSON syntax, and content type. The path parameter name and type must match the route and conversion.
Official sources
[Extractor guide](https://docs.rs/axum/0.8.9/axum/extract/)
[Error handling](https://docs.rs/axum/0.8.9/axum/error_handling/)
[Router reference](https://docs.rs/axum/0.8.9/axum/struct.Router.html)
[IntoResponse reference](https://docs.rs/axum/0.8.9/axum/response/trait.IntoResponse.html)