expression

Axum: combine path and body extractors

Request metadata can be extracted before a body-consuming extractor. A body is a stream that cannot generally be consumed twice. Put Json last and validate both the path and payload before acting. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 4: pear Common mistake: Putting Json before Path or attempting two independent body-consuming extractors.

Formal Syntax & Structure

rust syntaxrust
async fn handler(Path(id): Path<u32>, Json(data): Json<Input>)

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, extract::Path, routing::post};    #[derive(serde::Deserialize)]    struct Rename { name: String }    async fn rename(Path(id): Path<u32>, Json(input): Json<Rename>) -> String { format!("{id}: {}", input.name) }    let app = Router::new().route("/items/{id}/rename", post(rename));    let r = app.oneshot(Request::builder().method("POST").uri("/items/4/rename").header("content-type", "application/json").body(Body::from(r#"{"name":"pear"}"#)).unwrap()).await.unwrap();    println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 64).await.unwrap()).unwrap());}
Rust Reference