expression
Axum: per-route body limits
Different endpoints can have different body budgets. Here both use the same String extractor but each has its own small test limit. A real budget should be based on resource costs and expected payloads. In-memory standalone Cargo example. Expected stdout (not executed): 413 200 Common mistake: Setting a generous global limit just because one endpoint needs it.
Formal Syntax & Structure
rust syntaxrust
post(handler).layer(DefaultBodyLimit::max(n))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::{routing::post, extract::DefaultBodyLimit}; async fn accept(_: String) -> StatusCode { StatusCode::OK } let app = Router::new() .route("/small", post(accept).layer(DefaultBodyLimit::max(4))) .route("/larger", post(accept).layer(DefaultBodyLimit::max(8))); for path in ["/small", "/larger"] { let req = Request::builder().method("POST").uri(path).body(Body::from("12345")).unwrap(); println!("{}", app.clone().oneshot(req).await.unwrap().status().as_u16()); }}