Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Extractors and Responses

JSON and Form Bodies in Axum

Accept request bodies in Axum with Json<T>, Form<T>, String and Bytes: content-type rules, 400, 415 and 422 rejections, body size limits and validation patterns.

Path and query data are small and visible in the URL. Real input, such as a new user, a blog post or an uploaded file, travels in the request body. Axum gives you extractors for the common formats: Json<T> for APIs, Form<T> for HTML forms, and String or Bytes for raw data. All of them consume the body, so only one can appear in a handler, and it must be the last argument.

This lesson covers each extractor, the status codes you get when the input is wrong, the default size limit, and where validation belongs.

Json<T>

Rust
use axum::{http::StatusCode, routing::post, Json, Router};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct NewUser {
    name: String,
    email: String,
    age: Option<u8>,
}

#[derive(Serialize)]
struct User {
    id: u64,
    name: String,
    email: String,
}

async fn create_user(Json(input): Json<NewUser>) -> (StatusCode, Json<User>) {
    let user = User { id: 1, name: input.name, email: input.email };
    (StatusCode::CREATED, Json(user))
}

fn app() -> Router {
    Router::new().route("/users", post(create_user))
}

Json<T> does four things before your handler runs:

  1. Checks that the content-type header is application/json (or application/*+json).
  2. Buffers the whole body (up to the size limit).
  3. Parses it as JSON.
  4. Deserialises it into T, which is where missing or mistyped fields are detected.

The same Json type serialises responses, as you saw in your first server: the response gets content-type: application/json.

Which status code for which mistake?

What the client did Status Why
Sent no content-type, or text/plain 415 Unsupported Media Type step 1 failed
Sent broken JSON such as {"name": 400 Bad Request syntax error, step 3
Sent valid JSON of the wrong shape (missing email, age: "x") 422 Unprocessable Entity data error, step 4
Sent a body bigger than the limit 413 Payload Too Large step 2 failed

Remember the difference between 400 and 422: 400 means "I could not even read this", 422 means "I read it, and it does not fit what I expect". Your clients (and your logs) will thank you for keeping them apart. The rejection text tells the client which field is missing, for example Failed to deserialize the JSON body into the target type: missing field `email` at line 1 column 15.

Optional, default and unknown fields

  • Option<T> fields can be absent or null.
  • #[serde(default)] supplies a default value.
  • Unknown fields are ignored. Use #[serde(deny_unknown_fields)] when you want strictness, for example in a configuration endpoint.
  • #[serde(rename_all = "camelCase")] maps Rust's snake_case to the JavaScript style that front ends usually send.

Form<T>

HTML forms send application/x-www-form-urlencoded bodies: name=Ana&email=ana%40example.com. Form<T> parses them exactly like Query<T> parses a query string:

Rust
use axum::{routing::post, Form, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct Login {
    username: String,
    password: String,
}

async fn login(Form(data): Form<Login>) -> String {
    format!("welcome, {}", data.username)
}

On GET and HEAD requests Form reads the query string instead of the body. On other methods a wrong content-type gives 415, and a body that does not fit T is rejected with a 4xx. File uploads need multipart/form-data, which is handled by the Multipart extractor (headers, cookies and uploads).

Raw bodies: String, Bytes, Request

Rust
use axum::{body::Bytes, http::StatusCode};

async fn echo_text(body: String) -> String { body }               // UTF-8 text, 400 if invalid UTF-8
async fn size(body: Bytes) -> String { format!("{} bytes", body.len()) }

Use these for webhooks that need the exact bytes (to verify a signature), for plain text, or for formats such as Protobuf. For true streaming of huge bodies, take axum::body::Body (or Request) and read it frame by frame instead of buffering.

Body size limits

Axum buffers extractor bodies with a default limit of 2 MB. That protects you from a client streaming gigabytes into memory. Change it per router with DefaultBodyLimit:

Rust
use axum::extract::DefaultBodyLimit;

let app = Router::new()
    .route("/upload", post(upload))
    .layer(DefaultBodyLimit::max(25 * 1024 * 1024)); // 25 MB here

Use DefaultBodyLimit::disable() only if you stream the body yourself and apply another limit (tower_http::limit::RequestBodyLimitLayer). It is common to keep the default for JSON routes and raise it only for the upload route.

Where does validation go?

Deserialisation checks shape and types. It does not check rules: the email has an @, the age is under 150, the name is not empty. Validate after extraction:

Rust
impl NewUser {
    fn validate(&self) -> Result<(), String> {
        if self.name.trim().is_empty() { return Err("name must not be empty".into()); }
        if !self.email.contains('@') { return Err("email must contain @".into()); }
        Ok(())
    }
}

Return 422 with a list of problems. The custom extractors lesson shows how to wrap this into a ValidatedJson<T> extractor so handlers never see invalid data. Crates such as validator give you derive macros for the same job.

Stand-in: which rejection do I get?

This model implements the decision list above for a JSON body: content-type check, size limit, syntax check (a tiny brace and quote balance check, not a real parser) and a field check. It is not serde, but the order of checks and the resulting status codes match what Json<T> does.

Rust Stand-in: the checks behind Json extraction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Try changing LIMIT and the bodies. The order matters: a wrong content-type is rejected before anyone looks at the body.

Stand-in: form-urlencoded versus JSON

The same data can arrive in two encodings. This second model turns both into one Signup value, so you can see why Json<T> and Form<T> are interchangeable at the type level while the wire format differs. Percent-decoding is limited to the two sequences used here.

Rust Stand-in: one struct, two body formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A client posts {"name": to a Json<NewUser> route. Which status is returned?

    The JSON is syntactically invalid, which is a 400. A 422 is for valid JSON whose data does not fit the type.
  2. 2. A client sends valid JSON without the required email field. Which status is returned?

    The body parses, but deserialising into the target type fails: a data error, answered with 422.
  3. 3. Where must a body extractor such as Json<T> appear among the handler arguments?

    Json consumes the request body, so it must be the last argument. Extractors that read only the head can come before it.
  4. 4. What is the default limit for buffered bodies, and how do you raise it for one router?

    Axum limits buffered bodies to 2 MB by default. DefaultBodyLimit::max(n) raises or lowers it for the routes it wraps.

Summary

  • Json<T> checks the content type, buffers up to the limit, parses, then deserialises; wrong content-type is 415, bad syntax 400, wrong shape 422, too large 413.
  • Form<T> handles urlencoded bodies (and the query string on GET); String and Bytes give raw access.
  • Only one body extractor per handler, and it comes last.
  • The default body limit is 2 MB; adjust it with DefaultBodyLimit.
  • Deserialisation checks shape; business rules need explicit validation.

Next: Custom Extractors and Rejections