Serialize Deserialize derive pair

Learn how to use serde's Serialize and Deserialize derive macros together on a Rust struct to handle JSON requests and responses in Axum.

When you build a web API with Axum, you often need to accept JSON data from clients and send JSON data back. Rust's serde library provides two key traits for this: Serialize and Deserialize. Deriving both on the same struct gives you a single type that can be read from a request body and written into a response body without writing manual parsing or formatting code. This page explains how that works, why it is useful, and how to use it correctly.

What Serialize and Deserialize Mean

Serialize means taking a Rust value and turning it into a format that can be sent to another program, like JSON. Deserialize is the opposite: taking data in a format like JSON and converting it into a Rust value. In Rust, these conversions are defined as traits. The serde crate provides the traits, and the serde derive feature provides macros like #[derive(Serialize)] and #[derive(Deserialize)] that automatically implement those traits for your struct.

When a struct has both Serialize and Deserialize implemented, you can use the same type for two directions of data flow. Axum's Json extractor uses Deserialize to read the request body. Axum's Json response uses Serialize to write the response body. Deriving both on one struct is a common pattern for create, read, and update operations where the client sends a representation and the server echoes or stores a similar representation.

Setting Up the Dependencies

Your Cargo.toml must include axum, serde with the derive feature, and a runtime like tokio. A minimal example looks like this:

[package]
name = "serde-pair-example"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

The derive feature enables the Serialize and Deserialize macros. Without it, you would have to implement the traits manually, which is verbose and error-prone.

The derive feature is required:

If you forget to add features = ["derive"] to serde, the compiler will not find the Serialize and Deserialize macros. This is a very common source of confusion for beginners.

First Example with a User Struct

Start with a simple User struct that has a name and email field. Derive both Serialize and Deserialize. Then write a handler that accepts a Json<User> and returns a Json<User> as an echo.

// src/main.rs
use axum::{
    extract::Json,
    routing::post,
    Router,
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    email: String,
}
async fn echo_user(Json(user): Json<User>) -> Json<User> {
    Json(user)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/echo", post(echo_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here the Json extractor reads the request body and calls User's Deserialize implementation. If the JSON matches the struct, user is a valid User value. The handler then returns Json(user), which calls User's Serialize implementation to produce a JSON response. Run the server and test it with curl:

curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","email":"alice@example.com"}'

The response will be exactly the same JSON. This works because the same struct is used for both deserialization and serialization.

Both directions work:

If you see the identical JSON echoed back, you have successfully used both Serialize and Deserialize on one struct. This is the simplest possible demonstration of the derive pair.

How the Derive Macros Work

When you write #[derive(Serialize, Deserialize)] above a struct, the compiler generates two implementations. The Serialize implementation walks over each field of the struct and calls the appropriate serialization method for the field's type. The Deserialize implementation expects a JSON object, reads each field by name, and converts the value using the field's type's Deserialize implementation. If a field is missing or has the wrong type, the deserializer returns an error.

The generated code is efficient and does not require reflection at runtime. All the parsing logic is written by the macro at compile time, which means Rust knows exactly what to expect and can produce optimized code.

// The following is a simplified idea of what the derive generates.
// It is not the exact code, but shows the mapping concept.
impl Serialize for User {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // Imagine code that writes each field into a JSON object.
        // It would call serializer.serialize_struct, then serialize each field.
        // ...
    }
}
impl<'de> Deserialize<'de> for User {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Imagine code that reads each field from the JSON object.
        // It would check for missing fields and type mismatches.
        // ...
    }
}

You never need to write this code yourself. The derive macros handle it.

Customizing Field Names

Sometimes the JSON keys do not match the Rust field names exactly. For example, your Rust struct might use first_name, but the client sends "firstName". Use the #[serde(rename = "...")] attribute to map the JSON name to the Rust field.

#[derive(Serialize, Deserialize)]
struct User {
    #[serde(rename = "firstName")]
    first_name: String,
    #[serde(rename = "emailAddress")]
    email: String,
}

With this struct, the client sends:

{
  "firstName": "Alice",
  "emailAddress": "alice@example.com"
}

And the Rust struct receives first_name = "Alice", email = "alice@example.com". When the handler returns the same struct, the output will use the renamed keys (firstName and emailAddress) because Serialize also respects the rename attribute.

Rename applies to both directions:

The rename attribute affects both serialization and deserialization. If you want different names for input and output, you need separate attributes like #[serde(rename(serialize = "...", deserialize = "..."))].

Hiding Sensitive Fields

When a struct contains data that should never be sent back to the client, such as a password hash, you can still derive both traits but tell serde to skip that field during serialization. Use #[serde(skip_serializing_if = "Option::is_none")] on an Option field, or #[serde(skip_serializing)] to always skip it.

Consider a User struct that stores a password for internal use. We want to accept the password in the request body but not include it in any response.

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    email: String,
    #[serde(skip_serializing)]
    password: String,
}

Now the client can send a password in the request, and the server can use it internally (for example, to hash and store it), but when the server returns the User struct, the password field is omitted from the JSON output.

Test it with a handler that echoes the struct:

async fn create_user(Json(user): Json<User>) -> Json<User> {
    // In a real app you would hash and store the user, but here we just return it.
    Json(user)
}

Request:

{"name": "Alice", "email": "alice@example.com", "password": "secret"}

Response:

{"name": "Alice", "email": "alice@example.com"}

The password is accepted during deserialization but omitted during serialization.

Skipped fields are not deserialization errors:

If a field is marked skip_serializing, it is still required during deserialization unless you also add #[serde(default)] or use an Option. The above struct requires password to be present in the request JSON. If a client omits it, the request will be rejected with a deserialization error. Use #[serde(default)] if the field should be optional.

Using Separate Structs for Input and Output

The derive pair works on one struct, but sometimes the input and output shapes differ significantly. For example, you might want an input struct that requires a password, and an output struct that never has one. You can define two separate structs, each with only the needed derives.

#[derive(Deserialize)]
struct CreateUserRequest {
    name: String,
    email: String,
    password: String,
}
#[derive(Serialize)]
struct UserResponse {
    name: String,
    email: String,
}
async fn create_user(Json(input): Json<CreateUserRequest>) -> Json<UserResponse> {
    // In a real app, hash the password and store the user.
    let user = UserResponse {
        name: input.name,
        email: input.email,
    };
    Json(user)
}

Here CreateUserRequest only derives Deserialize because it is used only as an extractor. UserResponse only derives Serialize because it is used only as a response. This is a clean design that avoids accidental leakage and makes the intent clear.

However, the topic of this page is specifically the derive pair on one struct. The separate-struct pattern is a legitimate alternative when the data shapes differ. Use the derive pair when the same data shape is used in both directions and you want less code.

Common Mistakes and Fixes

Beginners often hit a few specific problems when using Serialize and Deserialize together.

Forgetting to derive Serialize

If you try to return Json<User> but User does not implement Serialize, the compiler gives an error. The Json response type requires T: Serialize.

// This will not compile
#[derive(Deserialize)]
struct User {
    name: String,
}
async fn echo_user(Json(user): Json<User>) -> Json<User> {
    Json(user) // error: the trait bound `User: Serialize` is not satisfied
}

Missing Serialize causes a compile-time error:

The error message will be something like "the trait bound User: Serialize is not satisfied". Add Serialize to the derive list to fix it.

Forgetting to derive Deserialize

If you try to extract Json<User> but User does not implement Deserialize, the handler cannot be used as an extractor.

// This will not compile
#[derive(Serialize)]
struct User {
    name: String,
}
async fn echo_user(Json(user): Json<User>) -> Json<User> {
    Json(user) // error: the trait bound `User: Deserialize<'_>` is not satisfied
}

Missing Deserialize causes a compile-time error:

The error message will be similar to "the trait bound User: Deserialize<'_> is not satisfied". Add Deserialize to the derive list.

Field Name Mismatch

If the JSON keys do not match the Rust field names and you do not use rename, deserialization fails with a "missing field" error: the unknown key is ignored, and the expected field is never supplied. By default, unknown fields are ignored unless you add #[serde(deny_unknown_fields)], but missing fields cause an error.

#[derive(Serialize, Deserialize)]
struct User {
    first_name: String,
    email: String,
}

A request with {"firstName": "Alice", "email": "..."} will fail because first_name is expected but firstName is unknown (ignored) and first_name is missing.

JSON keys are case-sensitive and must match exactly:

Rust field names are typically snake_case, while JSON often uses camelCase or other conventions. Always specify rename when the client sends different key names.

Missing serde dependency

If you forget to add serde to Cargo.toml, the derive macros will not be found. Make sure your Cargo.toml includes serde = { version = "1", features = ["derive"] }.

Real-World Example with CRUD Operations

Consider a simple in-memory todo list API. A Todo struct with id, text, and done fields can be used for both creating and listing todos if we derive both Serialize and Deserialize. This example also uses uuid::Uuid, so add uuid = { version = "1", features = ["v4"] } to the Cargo.toml shown above before compiling it.

use axum::{
    extract::{Path, State},
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use uuid::Uuid;
#[derive(Clone, Serialize, Deserialize)]
struct Todo {
    id: String,
    text: String,
    done: bool,
}
type TodoStore = Arc<Mutex<HashMap<String, Todo>>>;
async fn create_todo(
    State(store): State<TodoStore>,
    Json(new_todo): Json<Todo>,
) -> Json<Todo> {
    // In a real app, you would not trust the client's ID. Generate a new one.
    let mut store = store.lock().unwrap();
    let todo = Todo {
        id: Uuid::new_v4().to_string(),
        text: new_todo.text,
        done: false,
    };
    store.insert(todo.id.clone(), todo.clone());
    Json(todo)
}
async fn list_todos(State(store): State<TodoStore>) -> Json<Vec<Todo>> {
    let store = store.lock().unwrap();
    Json(store.values().cloned().collect())
}
#[tokio::main]
async fn main() {
    let store: TodoStore = Arc::new(Mutex::new(HashMap::new()));
    let app = Router::new()
        .route("/todos", post(create_todo).get(list_todos))
        .with_state(store);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

In this example, Todo is used as both a request body (Json<Todo> in create_todo) and a response body (Json<Todo> and Json<Vec<Todo>>). The derive pair makes this natural. Note that id is a plain String field, so it is required during deserialization: a client must send an id in the JSON, even though the handler throws it away and generates a new UUID. That is awkward, and it is exactly why a real API would use a separate CreateTodoRequest struct without an id field. If you keep one struct, add #[serde(default)] on id (so a missing id becomes an empty string) or make it Option<String>.

Production code often separates request and response models:

While deriving both on one struct works, production APIs often use separate input and output structs to handle missing fields, generated IDs, and sensitive data. The derive pair is still useful for internal models or simple echo endpoints.

Summary

Deriving Serialize and Deserialize together on a Rust struct gives you a single type that can be extracted from a JSON request body and returned as a JSON response with Axum's Json type. The derive macros generate the necessary conversion code at compile time, so you don't have to write it manually. Use attributes like rename and skip_serializing to control field mapping and omission. When the input and output shapes differ, consider separate structs with only the needed derive. The most common beginner errors are forgetting one of the derives or missing the derive feature in Cargo.toml. Once you understand this pair, you can build clean, type-safe JSON APIs in Axum with very little boilerplate.