Troubleshooting - Help and questions

Why must the Json extractor be the last argument of an axum handler?

#axum#extractors#json#compile-errorsasked 0 answers0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Extractors that read the request body (Json, Form, String, Bytes) consume it, and a body can only be read once, so axum accepts only one and only as the last argument. Move Json after Path, Query and State; #[debug_handler] prints the exact rule when the order is wrong.

Checked with rustc 1.93.0, axum 0.8.9 with the macros feature, tokio 1.54.1, Windows 11; the error below is pasted from cargo check

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

#1

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:

examples/f12b.rsrust
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));
}
text
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:

rust
async fn add(Path(id): Path<u32>, Json(note): Json<Note>) -> String { /* ... */ }

Common mistakes#

  • Using two body extractors (Json and String) 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 Json to find it. Whoever reads the body first uses it up unless the middleware puts a new body back.

Which extractors read the body?#

Json, Form, String, Bytes, Multipart and Request itself. Path, Query, State, HeaderMap and typed headers do not.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No answers yet

    No answers yet. If you know, answer it.