Symptom#
A handler with Json before Path does not compile. Without help the message is only about the Handler trait; with #[debug_handler] it says what is wrong:
use axum::{debug_handler, extract::Path, routing::post, Json, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct Note { text: String }
#[debug_handler]
async fn add(Json(note): Json<Note>, Path(id): Path<u32>) -> String {
format!("{id}: {}", note.text)
}
#[tokio::main]
async fn main() {
let _app: Router = Router::new().route("/notes/{id}", post(add));
}error: `Json<_>` consumes the request body and thus must be the last argument to the handler function
--> examples\f12b.rs:8:26
|
8 | async fn add(Json(note): Json<Note>, Path(id): Path<u32>) -> String {
| ^^^^
...Cause#
Extractors come in two kinds. Those built from the request's parts (method, URI, headers, path parameters, state) can be used in any number and any order. Those built from the body take the body away, so only one can exist and it must come last. The macro's message is the rule: "consumes the request body and thus must be the last argument".
Fix#
Reorder the arguments:
async fn add(Path(id): Path<u32>, Json(note): Json<Note>) -> String { /* ... */ }Common mistakes#
- Using two body extractors (
JsonandString) in one handler. Read the body once, as the type you need, and convert in code. - Reading the body in a middleware and then expecting the handler's
Jsonto find it. Whoever reads the body first uses it up unless the middleware puts a new body back.
Related questions#
Which extractors read the body?#
Json, Form, String, Bytes, Multipart and Request itself. Path, Query, State, HeaderMap and typed headers do not.
Sources#
- axum,
extractmodule (order of extractors): https://docs.rs/axum/0.8.9/axum/extract/index.html (read 2026-12-05) - axum,
debug_handler: https://docs.rs/axum/0.8.9/axum/attr.debug_handler.html (read 2026-12-05)