serde Deserialize for JSON Requests
Learn how serde's Deserialize trait powers JSON request parsing in Axum handlers, with derived structs, attributes, and common pitfalls for absolute beginners.
When an Axum handler receives a JSON request body, the Json extractor uses a library called serde to turn the raw JSON bytes into a Rust struct you can work with. The Json extractor is a handler argument that reads the request body and parses it as JSON. This page focuses on the Deserialize trait from serde, which is the mechanism that makes that conversion possible: how serde knows what shape your data should have, how to customize that shape, and what to watch out for when your JSON doesn't match.
What Is Deserialization?
Deserialization is the process of taking data in a format that's easy to send over a network (like a JSON string) and turning it into a structured, typed value in your programming language. JSON is just text. Your Rust program cannot comfortably work with raw text when you need to access fields, validate types, or pass data around. Deserialization transforms that text into a struct with named fields, typed values, and the safety of Rust's type system.
serde is the most popular Rust library for this job. It provides two core traits: Serialize (turning Rust values into a format like JSON) and Deserialize (turning a format like JSON into Rust values). When you use the Json extractor in Axum, it internally calls serde_json::from_slice on the buffered request body, and that function relies on your target type implementing Deserialize.
Adding serde to Your Project
You almost never implement Deserialize by hand. Instead, you derive it. Deriving means you add #[derive(Deserialize)] above your struct or enum, and at compile time serde generates the code needed to read JSON and fill your type. This requires the serde crate with its derive feature.
Open your Cargo.toml and add these dependencies:
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
The features = ["derive"] part tells cargo to include the derive macro, which is what lets you write #[derive(Deserialize)]. Without it, you'd have to implement the trait manually, which is verbose and error-prone.
A Basic Derived Struct
Start with the simplest possible example. Imagine a client sends this JSON to your server:
{
"name": "Alice",
"age": 30
}
You want to receive that data in a Rust struct. Define the struct and derive Deserialize:
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
}
That's all you need on the data side. Now use it with Axum's Json extractor:
use axum::{extract::Json, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
}
async fn create_user(Json(user): Json<User>) -> String {
format!("Created user {} who is {} years old", user.name, user.age)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
When a POST request arrives at /users with the JSON above, serde reads the body, looks for a name string and an age unsigned integer, and constructs a User. The Json extractor wraps that value, and pattern matching Json(user) gives you the inner User. The handler then returns a simple confirmation string.
Notice that the field names in the JSON exactly match the field names in the struct: name and age. By default, serde expects that matching. Any mismatch leads to an error, which we'll explore later.
How Axum Uses Deserialize Under the Hood
It's worth pausing to see the connection between Json and Deserialize. When you write Json<User> as a handler argument, Axum sees that User implements Deserialize. It buffers the request body as bytes, then calls serde_json::from_slice with those bytes. That function is generic over any type implementing Deserialize, so it creates a User from the JSON. If the JSON is malformed or doesn't match the struct, serde_json::from_slice returns an error, and Axum turns that error into an HTTP response (usually a 400 Bad Request or 422 Unprocessable Entity, depending on the specific rejection).
You don't need to know every internal step, but understanding this flow helps later when you debug deserialization problems: the error messages come from serde_json, not from Axum itself.
Deserializing Different JSON Shapes
Real APIs send more varied JSON. Your struct can contain nested objects, arrays, optional values, and enums. Let's build up gradually.
Nested Structs
Suppose the JSON includes an address object:
{
"name": "Alice",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Springfield"
}
}
Define a separate struct for the address and include it as a field:
use serde::Deserialize;
#[derive(Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
address: Address,
}
serde automatically recurses into the nested object because Address also implements Deserialize. There's no limit to nesting depth.
Optional Fields
Often a field may be missing entirely. Use Option<T> to allow that:
#[derive(Deserialize)]
struct User {
name: String,
age: Option<u32>,
}
Now JSON can omit age entirely, or set it to null:
{ "name": "Alice" }
Both cases result in age: None. If you want to distinguish between missing and null, you can use Option<Option<T>> or custom deserialization, but that's rarely needed.
Vec and HashMap
For dynamic collections, use Vec<T> for arrays and HashMap<String, V> for objects with unknown keys:
use std::collections::HashMap;
#[derive(Deserialize)]
struct Team {
name: String,
members: Vec<String>,
attributes: HashMap<String, i32>,
}
This would match JSON like:
{
"name": "Rust Team",
"members": ["Alice", "Bob", "Carol"],
"attributes": {
"size": 42,
"founded": 2015
}
}
Note: attributes is HashMap<String, i32>, so every value must be an integer. A value like "Remote" would fail, because a string cannot be parsed as an i32. If you need mixed types, you'd use serde_json::Value.
Customizing Field Names with serde Attributes
Sometimes the JSON uses different naming conventions than your Rust struct. For instance, JavaScript code often sends userName while Rust prefers user_name. You can rename fields with the #[serde(rename = "...")] attribute.
#[derive(Deserialize)]
struct User {
#[serde(rename = "userName")]
user_name: String,
age: u32,
}
Now this JSON works:
{
"userName": "Alice",
"age": 30
}
You can also rename the entire struct to a different top-level name, though that's rarely needed for JSON because the top-level name doesn't appear in the data.
For a whole set of fields following a pattern, use container-level attributes like #[serde(rename_all = "camelCase")] on the struct:
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct User {
user_name: String, // matches "userName"
first_name: String, // matches "firstName"
last_name: String, // matches "lastName"
}
This is a huge time-saver when integrating with APIs that use camelCase.
Rename All Options:
The rename_all attribute accepts values like "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE". Pick the one that matches your JSON.
Handling Missing Fields with Default Values
If a field may be absent and you want to provide a default, use #[serde(default)]. This requires the field's type to implement Default (or you can provide a custom function).
#[derive(Deserialize)]
struct Config {
host: String,
#[serde(default)]
port: u16,
}
If JSON is { "host": "localhost" }, port becomes 0 because u16::default() is 0. That's often not what you want. You can specify a custom default function:
fn default_port() -> u16 { 8080 }
#[derive(Deserialize)]
struct Config {
host: String,
#[serde(default = "default_port")]
port: u16,
}
Now missing port yields 8080. You can also use #[serde(default)] on the whole struct to make all fields optional with their type's Default, but that's less explicit.
Zero Values Can Be Surprising:
Using #[serde(default)] without a custom function can lead to unexpected values: 0 for numbers, empty string for String, empty vector for Vec. Always consider whether that's actually the desired behavior. Often, Option<T> is clearer because it represents "missing" explicitly instead of silently substituting a zero-like value.
Accepting Unknown Fields
By default, serde ignores fields in the JSON that are not present in your struct. This is the normal, forgiving behaviour: if the client sends { "name": "Alice", "age": 30, "admin": true } and your struct only has name and age, the admin key is simply skipped and deserialization succeeds. So if a client sends "nmae": "Alice" instead of "name", serde does not complain about the extra key; it complains that the required field name is missing.
If you want strictness instead, add the container attribute #[serde(deny_unknown_fields)]. Then any key that is not a field of the struct makes deserialization fail with an "unknown field" error:
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct User {
name: String,
age: u32,
}
Now { "name": "Alice", "age": 30, "admin": true } fails, because admin is not a field. There is no #[serde(ignore_unknown_fields)] attribute: ignoring unknown fields is already the default, so there is nothing to opt into.
Silently Ignoring Data:
Ignoring unknown fields can hide real bugs. If a client sends "user_name" and your struct expects "name", the extra key is dropped and deserialization then fails because the required field name is missing, which is a clear error. But if the field it should have matched is optional, the typo would silently become None. Use deny_unknown_fields when you want typos and schema drift to fail loudly.
Deserializing Enums
Enums are great for representing a set of possible values. Consider a JSON field that can be one of several strings:
{
"role": "admin"
}
Define an enum and derive Deserialize:
#[derive(Deserialize)]
enum Role {
Admin,
User,
Guest,
}
#[derive(Deserialize)]
struct Person {
name: String,
role: Role,
}
By default, serde matches variant names exactly and case-sensitively, so it expects "Admin", "User", "Guest" unless you rename variants:
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Role {
Admin,
User,
Guest,
}
Now the JSON should use "admin", "user", "guest".
You can also use enums with data, called "tagged" or "internally tagged" enums, but that's a more advanced topic. For simple string enums, the above works perfectly.
Deserializing into serde_json::Value
Sometimes you don't know the exact structure of the incoming JSON, or you want to inspect it dynamically. Use serde_json::Value, which is an enum that can represent any JSON value (object, array, string, number, boolean, or null). This type already implements Deserialize, so you can use it directly:
use axum::extract::Json;
use serde_json::Value;
async fn handle_json(Json(payload): Json<Value>) -> String {
// Inspect the value at runtime
if let Some(name) = payload.get("name").and_then(|v| v.as_str()) {
format!("Received name: {}", name)
} else {
"No name field".to_string()
}
}
This approach is flexible but loses type safety and compile-time checks. For most handlers, a concrete struct is better because errors are caught early and you get nice documentation via the struct definition.
Common Mistakes and How to Avoid Them
Beginners often run into several recurring issues with serde Deserialize and the Json extractor. Knowing these will save hours of debugging.
1. Missing Content-Type: application/json Header
The Axum Json extractor checks that the request has the header Content-Type: application/json. If it's missing, the extractor returns a MissingJsonContentType rejection, and your handler never runs. This is not a serde error; it happens before deserialization even starts. Make sure your client sends that header.
Content-Type Is Required:
Sending JSON via curl without -H "Content-Type: application/json" will cause Axum to reject the request with a 415 error. Always include that header when testing JSON endpoints.
2. Type Mismatch Between JSON and Rust
If JSON has "age": "30" (a string) but your struct field is u32, deserialization fails. The error message from serde will point to the line and column where it happened. Read those errors carefully; they often tell you exactly which field caused the problem.
3. Unknown Fields Are Ignored by Default
As mentioned, serde ignores unknown fields by default, so an external service adding new fields will not break your handler. That is usually what you want. If you would rather fail loudly on unexpected keys, add #[serde(deny_unknown_fields)] to the struct. The common surprise is the opposite one: a misspelled key like "nmae" does not produce an "unknown field" error, it produces a "missing field name" error, because the required field was never supplied.
4. Forgetting to Derive Deserialize
This sounds obvious, but a missing #[derive(Deserialize)] results in a compile error when you use Json<MyStruct>, because MyStruct doesn't implement the required trait. The compiler error will say something like "the trait bound MyStruct: Deserialize<'_> is not satisfied". The fix is to add the derive and make sure serde with the derive feature is in Cargo.toml.
5. Using String When You Need an Integer or Float
JSON numbers can be integers or floating-point. Rust's u32 will accept integer numbers like 30 but not 30.5. If your client might send decimal values, use f64 or f32. Also note that JSON doesn't distinguish between int and float; serde will try to convert a number to the target type. 30.0 can be deserialized into f64 but not into u32 (because u32::deserialize expects an integer token without a fractional part). This is a common source of errors when dealing with numeric fields.
Deserializing Directly with serde_json
While the Json extractor is the standard way in Axum, sometimes you need more control. For instance, you might want to read the raw body as a String and then parse it yourself. The String extractor (from Axum) gives you the body text, and then you can call serde_json::from_str manually. This is useful when you need to perform custom validation before parsing, or when you want to handle different content types.
Here's an example that reads the body as a string, parses it, and returns a custom error message on failure:
use axum::{http::StatusCode, response::{IntoResponse, Response}, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
}
async fn create_user_manual(body: String) -> Response {
match serde_json::from_str::<User>(&body) {
Ok(user) => (
StatusCode::CREATED,
format!("Created user {} (age {})", user.name, user.age),
).into_response(),
Err(e) => (
StatusCode::BAD_REQUEST,
format!("Invalid JSON: {}", e),
).into_response(),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users-manual", post(create_user_manual));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Note that this handler takes String, which is a body-consuming extractor. Because it consumes the body, you cannot also use Json in the same handler. This approach bypasses Axum's built-in Json rejection handling and gives you full control over the error response. It's also a good way to learn how serde works without Axum's wrapper.
You Can Test Deserialization Standalone:
If you're ever unsure whether your struct matches your JSON, write a small Rust test using serde_json::from_str directly. That isolates the serde part from Axum and makes debugging easier.
Setting Up serde for JSON Requests from Scratch
If you're starting a new Axum project and want to accept JSON bodies, follow these steps in order.
Step 1: Create a new Rust project
Run cargo new my-json-api and cd my-json-api. This sets up a basic binary crate.
Step 2: Add dependencies to Cargo.toml
Open Cargo.toml and add axum, serde with derive, serde_json, and tokio with macros and rt-multi-thread features. The file should look like the one shown earlier.
Step 3: Define your data struct with derive
In src/main.rs, create a struct representing the expected JSON and add #[derive(Deserialize)] above it.
Step 4: Write a handler using Json extractor
Write an async function that takes Json<YourStruct> as an argument. In the function body, access the inner data.
Step 5: Set up the Router and start the server
Create a Router, add a route for your handler (usually post), and call axum::serve with a TcpListener.
Step 6: Test with curl
Send a POST request with a JSON body and the correct Content-Type header. Check that your handler runs and the response is as expected.
Real-World Usage Patterns
In production applications, you'll often define structs that mirror the exact JSON contract of your API. These structs live in a separate module (like models.rs) and are shared between request and response types. You'll also see extensive use of Option, rename_all, and default values to handle API evolution gracefully. Because serde derive is so concise, it's rare to hand-implement Deserialize unless you have very unusual requirements (like deserializing from multiple formats or doing custom validation during parsing).
A common pattern is to have a request struct for incoming data and a separate entity struct for your database. Deserialization is only the first step: after Json(payload) gives you the request struct, you often transform it into a database model. Keeping those concerns separate makes your code easier to maintain. The split is usually small:
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
}
struct UserRow {
id: u64,
name: String,
email: String,
}
fn to_row(id: u64, req: CreateUserRequest) -> UserRow {
UserRow {
id,
name: req.name,
email: req.email,
}
}
The request struct only describes what the client may send, so it never carries a database id or a password hash. The entity struct only describes what the database stores, so it never has to match the client's JSON. The handler converts one into the other, and each side can change without breaking the other.
Summary
The Deserialize trait from serde is what allows the Json extractor to turn raw JSON bytes into typed Rust values. By deriving Deserialize on your structs and enums, you tell serde how to map JSON fields to Rust fields. Attributes like rename, default, and deny_unknown_fields give you fine-grained control over that mapping without writing any manual parsing code. Understanding these attributes and the common failure modes - missing Content-Type, missing fields, type mismatches - will let you build robust JSON APIs with Axum quickly.
The rule that ties the page together is this: serde is strict about shape and forgiving about extras. A missing required field or a wrong type always fails, and that failure is a 400 or 422 before your handler runs. An unknown field is ignored by default, so a client that sends one extra key does not break your endpoint, and a typo in a key surfaces as a missing-field error for the field you actually wanted, not as an unknown-field error. When that forgiveness hides a real mistake, such as a misspelled optional field silently becoming None, deny_unknown_fields turns the same input into a loud failure. Choose the default when your API evolves and clients may send more than you expect; choose strictness when a typo must never pass silently.