JSON Extractor in Axum

Learn how to extract and deserialize JSON request bodies using the Json extractor in Axum, from basic typed structs to flexible Value parsing and error handling.

When a client sends data to your server in JSON format, your handler needs a way to turn that raw text into a usable Rust value. In Axum, the Json extractor does that work for you. It reads the request body, parses the JSON, and gives you a typed value - so you can work with plain structs instead of manipulating strings.

This page focuses exclusively on using Json as an extractor - that is, as an argument in your handler that pulls data from the incoming request. By the end you'll be able to write handlers that accept JSON payloads, know what happens when the JSON is malformed, and handle errors gracefully when needed.

What is an extractor?:

In Axum, an extractor is a type that implements the FromRequest or FromRequestParts trait. Handlers can take any number of extractors as arguments, and Axum runs them automatically before calling your handler. Json<T> is one such extractor.

How the Json Extractor Works

The Json type is defined as pub struct Json<T>(pub T);. It's a generic wrapper around some inner value T. When you write Json<CreateUser> as a handler argument, Axum knows it needs to read the request body, interpret it as JSON, and try to build a CreateUser value from it.

For this to work, T must implement the DeserializeOwned trait from the serde crate. In practice this means you derive Deserialize on your struct (or use a type like serde_json::Value that already implements it). The extraction process involves three steps:

  1. Axum checks that the request has a Content-Type: application/json header. If not, it rejects the request immediately.
  2. The entire body is buffered into memory and parsed as JSON syntax.
  3. The parsed JSON is deserialized into your target type T.

If any of those steps fail, the handler is never called. Instead, Axum returns a JsonRejection - a specific error type that describes what went wrong.

The body can only be consumed once:

Since parsing JSON requires reading the entire request body, the Json extractor must be the last argument in your handler if you have multiple extractors. Axum enforces this at compile time: the last argument must implement FromRequest (which consumes the body), while all earlier arguments must implement FromRequestParts (which does not).

Basic Example: Receiving a JSON Object

Let's start with the simplest possible case. You want to accept a JSON object with two string fields: email and password. First, define a struct that matches the shape of the JSON and derive Deserialize:

use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}

Now write a handler that takes Json<CreateUser>:

use axum::{
    extract::Json,
    routing::post,
    Router,
};
async fn create_user(Json(payload): Json<CreateUser>) {
    // payload is a CreateUser
    println!("Creating user with email: {}", payload.email);
    // In a real app you'd save the user to a database here.
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

There are a few things worth noticing in this example. The handler signature Json(payload): Json<CreateUser> uses a pattern match. Json is a tuple struct with one public field, so you can destructure it directly in the parameter list. Inside the handler, payload is a normal CreateUser value - you can access its fields as usual.

Also note the use statements. We import Json from axum::extract, and post from axum::routing. The CreateUser struct must derive Deserialize, which comes from the serde crate. Add these dependencies to Cargo.toml:

[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }

The json feature of axum is enabled by default, so you don't need to add it explicitly. serde_json is needed for the Value example later on this page.

Correct setup:

If your dependencies are correct and you send a request with the right header and body, the handler will run and print the email. This is the sign that everything is wired properly.

Now test it with curl:

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email":"alice@example.com","password":"secret123"}'

You should see the handler output something like Creating user with email: alice@example.com.

What Happens When JSON Is Invalid

The Json extractor is strict. If the request doesn't meet its expectations, your handler will not run, and Axum will return an error response instead. There are four common failure scenarios, each corresponding to a variant of JsonRejection:

  • Missing Content-Type: application/json header - Axum returns a JsonRejection::MissingJsonContentType.
  • Invalid JSON syntax - the body isn't parseable as JSON at all; this is JsonRejection::JsonSyntaxError.
  • Valid JSON but wrong shape for the target type - for example, sending a number where a string is expected, or missing a required field; this is JsonRejection::JsonDataError.
  • Buffering error - reading the body from the network fails, which is JsonRejection::BytesRejection.

These rejections are converted into HTTP responses automatically. For example, a missing content type returns 415 Unsupported Media Type, malformed JSON syntax returns 400 Bad Request, and a JSON body that does not match the target type returns 422 Unprocessable Entity.

You can see these errors yourself by sending malformed requests:

# Missing Content-Type header
curl -X POST http://localhost:3000/users \
  -d '{"email":"alice@example.com","password":"secret"}'
# Invalid JSON syntax
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d 'not json at all'
# Wrong field type
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email":123,"password":"secret"}'

Forgetting the Content-Type header is the top beginner mistake:

Many HTTP clients (and sometimes even fetch in the browser) do not automatically set Content-Type: application/json when you send a JSON string. If your handler is never called and you get a 415 error, check the header first.

Handling Rejections Inside the Handler

Sometimes you want to customize the error response or log something specific when extraction fails. You can do that by taking the extractor as Result<Json<T>, JsonRejection> instead of plain Json<T>. Then you match on the result inside your handler:

use axum::{
    extract::{Json, rejection::JsonRejection},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    password: String,
}
async fn create_user(
    payload: Result<Json<CreateUser>, JsonRejection>,
) -> Response {
    match payload {
        Ok(Json(user)) => {
            // Handle success
            format!("Created user {}", user.email).into_response()
        }
        Err(JsonRejection::MissingJsonContentType(_)) => {
            (StatusCode::UNSUPPORTED_MEDIA_TYPE, "Missing Content-Type header").into_response()
        }
        Err(JsonRejection::JsonSyntaxError(_)) => {
            (StatusCode::BAD_REQUEST, "Invalid JSON syntax").into_response()
        }
        Err(JsonRejection::JsonDataError(_)) => {
            (StatusCode::UNPROCESSABLE_ENTITY, "JSON data did not match expected shape").into_response()
        }
        Err(JsonRejection::BytesRejection(_)) => {
            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to read body").into_response()
        }
        Err(_) => {
            (StatusCode::INTERNAL_SERVER_ERROR, "Unknown error").into_response()
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The JsonRejection type is an enum with the four variants we just described. Each variant carries an inner error type that gives more details, but for a beginner it's enough to match on the variant name. This approach gives you full control over the HTTP status code and body for each failure case.

When to use Result<Json<T>, JsonRejection>:

Use this pattern when you need to customize error responses for a specific handler. If the default error responses are acceptable, you can keep the plain Json<T> extractor - Axum will generate reasonable errors for you.

Using serde_json::Value for Flexible JSON

Sometimes you don't know the exact structure of the JSON you'll receive, or you need to accept a variety of shapes. For those cases, you can use serde_json::Value as the inner type. Value is an enum that can represent any valid JSON value: objects, arrays, strings, numbers, booleans, or null.

Here's a handler that accepts any JSON object and echoes back a field if it exists:

use axum::{
    extract::Json,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use serde_json::{json, Value};
async fn echo_payload(Json(payload): Json<Value>) -> Response {
    // payload is a serde_json::Value
    if let Some(name) = payload.get("name").and_then(|v| v.as_str()) {
        (StatusCode::OK, json!({ "message": format!("Hello, {}!", name) })).into_response()
    } else {
        (StatusCode::BAD_REQUEST, json!({ "error": "Missing 'name' field" })).into_response()
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo_payload));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

serde_json::Value itself implements DeserializeOwned, so it can be used directly as the inner type of Json. This approach gives you maximum flexibility but sacrifices compile-time checking of field names and types. You'll need to perform runtime checks (like get and as_str) to safely access data.

Use Value when you're building a generic API gateway, inspecting arbitrary JSON, or gradually prototyping without a fixed schema. For production endpoints with a known contract, a typed struct is almost always better.

Nested and Optional Fields

Real-world JSON often has nested objects or optional fields. Serde's derive macro handles both automatically. Consider this payload:

{
  "email": "alice@example.com",
  "profile": {
    "display_name": "Alice",
    "age": 30
  },
  "newsletter": true
}

You can model it with nested structs and Option:

use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    profile: Profile,
    newsletter: Option<bool>,
}
#[derive(Deserialize)]
struct Profile {
    display_name: String,
    age: u32,
}

If a field is missing and you declared it as Option<T>, serde will set it to None. If it's missing and the field is not Option, deserialization fails with a JsonDataError. That's an important distinction to remember.

use axum::{
    extract::Json,
    routing::post,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    email: String,
    profile: Profile,
    newsletter: Option<bool>,
}
#[derive(Deserialize)]
struct Profile {
    display_name: String,
    age: u32,
}
async fn create_user(Json(payload): Json<CreateUser>) {
    let newsletter = payload.newsletter.unwrap_or(false);
    println!(
        "User {} ({}) subscribed: {}",
        payload.profile.display_name,
        payload.email,
        newsletter
    );
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test with:

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email":"alice@example.com","profile":{"display_name":"Alice","age":30},"newsletter":true}'

And then try omitting newsletter:

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"email":"alice@example.com","profile":{"display_name":"Alice","age":30}}'

Both will succeed because newsletter is Option<bool>. If newsletter were a plain bool instead of Option<bool>, the second request would fail because the field is required. (Removing the field from the struct entirely would not make it fail: serde ignores unknown fields by default, so the extra newsletter key in the JSON would simply be skipped.)

Where the Json Extractor Fits in the Handler Signature

Remember that extractors run left to right, and only the last one may consume the body. This means Json<T> should always be the final parameter. Here's a handler that uses Path, Query, and Json together correctly:

use axum::{
    extract::{Path, Query, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
use uuid::Uuid; // add `uuid = { version = "1", features = ["serde", "v4"] }` to Cargo.toml
#[derive(Deserialize)]
struct CreateComment {
    text: String,
}
#[derive(Deserialize)]
struct Pagination {
    page: usize,
    per_page: usize,
}
async fn add_comment(
    Path(post_id): Path<Uuid>,
    Query(pagination): Query<Pagination>,
    Json(comment): Json<CreateComment>,
) {
    println!(
        "Adding comment to post {} on page {} ({} per page): {}",
        post_id, pagination.page, pagination.per_page, comment.text
    );
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/posts/{id}/comments", post(add_comment));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Path and Query extract from the URI without touching the body, so they can appear before Json. If you try to place Json before another extractor, the code will not compile - Axum enforces the rule through the trait system. Note that both fields of Pagination here are required, so a request without ?page= and ?per_page= is rejected before the handler runs; making them Option or giving them defaults is the fix if the endpoint should work without them.

Order matters: body consumer last:

You cannot have more than one body-consuming extractor in a handler. If you need both String and Json, for instance, that's impossible because both would try to read the body. Choose one.

Summary

The Json extractor is the bridge between raw JSON bytes in an HTTP request and typed Rust data. You've seen how to define a struct with Deserialize, use Json<T> as the last handler argument, and let Axum handle parsing automatically. You also learned how to take control of errors using Result<Json<T>, JsonRejection>, and how to fall back to serde_json::Value when the schema is unknown.

A few key points to remember: always send the Content-Type: application/json header from the client, keep the Json extractor last in your handler signature, and prefer typed structs over Value for maintainable code.

The choice that shapes an endpoint most is how much control you keep over failure. Plain Json<T> is right while you are prototyping and Axum's plain text rejections are acceptable: missing content type gets a 415, bad syntax a 400, and a shape mismatch a 422, all before your handler runs. Switch to Result<Json<T>, JsonRejection> the moment your API promises one error shape everywhere, and keep the same status codes Axum uses by default unless you have a reason to change them. And when the JSON shape is unknown, reach for Value only as a temporary step: the moment the contract settles, a typed struct catches the same mistakes at compile time instead of at runtime.