Axum Form Feature and Form Extractor

Learn how to use the axum form feature to handle URL-encoded form data in your Axum web application, including reading forms from requests and returning them in responses.

When you want to accept traditional HTML form submissions in an Axum server, the form feature is what provides that ability. It is on by default in axum 0.8, and this page explains how the Form type works for both incoming and outgoing data, and how to avoid the mistakes that trip up most beginners.

What the form Feature Adds

The axum crate organizes some of its functionality behind feature flags. Feature flags let you include only the parts of the crate you actually use, keeping compile times and binary sizes smaller. The form feature enables the axum::Form type, which is an extractor and a response type for application/x-www-form-urlencoded data.

In axum 0.8, form is one of the default features, so a plain axum = "0.8" dependency already includes axum::Form - there is nothing extra to turn on. The feature only matters if you turn off the defaults with default-features = false: then axum::Form does not exist until you add "form" back to the features list.

That is the exact format an HTML <form> sends when a user clicks submit and the form has no enctype attribute or has enctype="application/x-www-form-urlencoded". It looks like this inside an HTTP request body:

username=alice&password=secret123

The form Feature in Cargo.toml

Open your project's Cargo.toml. Your [dependencies] section already contains axum, tokio, and serde. Because form is a default feature of axum 0.8, a plain axum dependency already gives you Form - you do not need to add anything.

Here is the complete Cargo.toml alongside the other core dependencies:

[package]
name = "my-axum-app"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

You only need to name the feature explicitly if you turned off the defaults, for example axum = { version = "0.8", default-features = false, features = ["form", "http1", "tokio"] }. Without that, axum::Form is not compiled in. The http1 and tokio entries are needed too: without http1 the server itself (axum::serve) does not exist, and without tokio the runtime integration is missing.

The serde dependency with the derive feature is essential because Form<T> requires the inner type T to implement serde::Deserialize when used as an extractor, and serde::Serialize when used as a response. If you have not added serde yet, do it now.

Feature Flags Are Additive:

You can list multiple features for the same crate inside the same array. Both form and json are already on by default in axum 0.8, so you would only write them out when you have turned off the defaults. A feature you do need to name explicitly is a non-default one, for example features = ["multipart"] for file uploads. Each feature unlocks a separate part of the crate.

After changing Cargo.toml, run cargo build so Cargo downloads the latest compatible version of axum and compiles the Form type into your project.

Understanding How Form Reads Incoming Data

Form<T> behaves differently depending on the HTTP method of the incoming request. This is important because it matches how web browsers actually submit forms.

  • If the request uses GET or HEAD, Form<T> reads the data from the query string in the URL. For example, http://localhost:3000/signup?username=alice&password=secret.
  • If the request uses any other method (like POST, PUT, PATCH), Form<T> reads the data from the request body, and the request must have the Content-Type header set to application/x-www-form-urlencoded.

This dual behavior is intentional. A browser that sends a GET form puts the data in the URL. A browser that sends a POST form puts the data in the body with that specific content type. Axum's Form handles both automatically.

Multipart Forms Are Different:

If an HTML form uses enctype="multipart/form-data" (common for file uploads), Form will not work. That requires a separate Multipart extractor and a different feature flag. Do not confuse the two.

A Minimal Working Example

Let's create a server that accepts a POST request to /login with form fields username and password. The handler will read those fields, do something with them (in this case, just echo them back), and return a plain string.

First, make sure your src/main.rs contains this code:

use axum::{
    routing::post,
    Router,
    Form,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}
async fn login_handler(Form(input): Form<LoginForm>) -> String {
    format!("Login attempt for user: {}", input.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/login", post(login_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Here is what each part does:

  • #[derive(Deserialize)] tells serde to generate the code that can parse the URL-encoded string username=alice&password=secret into a LoginForm struct. The field names in the struct must match the keys in the form data exactly (case-sensitive).
  • The handler signature Form(input): Form<LoginForm> is the extractor. Axum sees the Form parameter, checks the request method and content type, reads the raw data, calls serde's deserialization, and gives you the populated struct.
  • If deserialization fails, Axum automatically returns an error response. For a POST body, a missing field such as password gives a 422 Unprocessable Entity response with a message like Failed to deserialize form body: missing field 'password'. For a GET request, where the data comes from the query string, the same kind of failure gives a 400 Bad Request response instead.

Run the server with cargo run. In a second terminal, send a POST request using curl:

curl -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=alice&password=secret123"

You should see the response:

Login attempt for user: alice

If you omit the Content-Type header, Axum will not recognize the body as form data. The request will fail with a 415 Unsupported Media Type error. This is a common mistake, so always include that header when testing with curl.

If You See the Greeting, It Works:

A successful output like Login attempt for user: alice confirms that the feature is enabled, serde is working, and the Form extractor parsed the body correctly.

Using Form with GET Query Strings

Because Form reads from the query string for GET requests, you can use the same struct for both GET and POST forms. This is handy when you have a search form or a filter form that submits via GET.

Add this handler to the same file:

use axum::routing::get;
// same LoginForm struct as before
async fn search_handler(Form(query): Form<LoginForm>) -> String {
    format!(
        "Searching for username: {} with password: {}",
        query.username, query.password
    )
}
// inside main(), add another route:
let app = Router::new()
    .route("/login", post(login_handler))
    .route("/search", get(search_handler));

Now visit or curl this URL:

curl "http://127.0.0.1:3000/search?username=alice&password=secret123"

The output:

Searching for username: alice with password: secret123

Notice that the handler did not need to know whether the data came from the URL or the body. Form handled both cases based on the HTTP method. This is different from the Query extractor, which only reads from the query string regardless of method.

Returning Form as a Response

Form can also be used on the return side of a handler. If a handler returns Form<T>, Axum serializes T into application/x-www-form-urlencoded format and sets the appropriate Content-Type header.

This is useful when you want to respond with a small set of key-value pairs in a format that a client already knows how to parse.

Add this code to your project:

use axum::response::IntoResponse;
use serde::Serialize;
#[derive(Serialize)]
struct Payload {
    status: String,
    count: u32,
}
async fn form_response_handler() -> Form<Payload> {
    Form(Payload {
        status: "ok".to_string(),
        count: 42,
    })
}
// add route:
let app = Router::new()
    .route("/login", post(login_handler))
    .route("/search", get(search_handler))
    .route("/payload", get(form_response_handler));

Now fetch /payload:

curl http://127.0.0.1:3000/payload

The response body will be:

status=ok&count=42

The Content-Type header will be application/x-www-form-urlencoded. This is exactly the same format that was sent in the request body earlier, so it can be parsed by a client using a Form extractor on the other side.

Handling Optional and Default Fields

In real forms, users might leave some fields empty, or you may want to provide default values. Serde works with Option<T> and #[serde(default)] just like with JSON or query strings.

Modify the LoginForm struct to make the password field optional and add an optional remember_me boolean with a default value:

#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: Option<String>,
    #[serde(default)]
    remember_me: bool,
}

Now the handler can access input.password as an Option<String>. If the client does not send a password field, it will be None. The remember_me field will be false by default if the client does not include it.

Test with a POST that omits password and remember_me:

curl -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=bob"

The handler still works because password becomes None and remember_me becomes false. Update the handler to show this:

async fn login_handler(Form(input): Form<LoginForm>) -> String {
    let password_msg = match input.password {
        Some(p) => format!("password: {}", p),
        None => "no password provided".to_string(),
    };
    format!(
        "User: {} | {} | remember_me: {}",
        input.username, password_msg, input.remember_me
    )
}

The output will be:

User: bob | no password provided | remember_me: false

If you send remember_me=true, it becomes true. If you send remember_me=false, it stays false.

Nested Form Data with Serde

Form data is flat by nature: just key-value pairs separated by &. Axum's Form parses it with serde_urlencoded, and that parser only understands flat structs - it does not split keys on brackets, so there is no way to fill a nested struct from form data. A key like address[city] is treated as one literal key named address[city], not as a field address containing a field city. If your struct declares a nested field, the request fails because that field is never filled - for example, a struct with an address: Address field receiving address[city]=Berlin gets a 422 Unprocessable Entity response with Failed to deserialize form body: missing field 'address'. And if the struct has no address field at all, the bracket key is simply ignored, and the request fails on whatever flat field is actually missing instead.

So keep your form structs flat, with one field per key:

#[derive(Deserialize)]
struct SignupForm {
    username: String,
    city: String,
    country: String,
}

The form data for this struct looks like:

username=alice&city=Berlin&country=Germany

Test it with curl:

curl -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=alice&city=Berlin&country=Germany"

Add the handler:

async fn signup_handler(Form(input): Form<SignupForm>) -> String {
    format!(
        "{} lives in {}, {}",
        input.username, input.city, input.country
    )
}

Route it with .route("/signup", post(signup_handler)).

The output will be:

alice lives in Berlin, Germany

If you need genuinely nested data, send JSON with the Json extractor instead - URL-encoded forms are the wrong tool for nested objects.

What Happens If You Turn Off the Default Features

With a normal axum = "0.8" dependency, form is already enabled and axum::Form just works - there is no feature flag to forget. The only way to lose Form is to turn off the defaults, for example with axum = { version = "0.8", default-features = false } and no "form" in the features list. Then the axum::Form type is not compiled, and trying to use it produces a compile-time error:

error[E0432]: unresolved import `axum::Form`
  --> src/main.rs:3:5
   |
3  | use axum::Form;
   |     ^^^^^^^^^^ no `Form` in the root

If you see that, add "form" to the features list of your axum dependency and rebuild. The compiler error is helpful but can be confusing if you don't know that Form is behind a feature flag.

Missing Feature Causes Hard-to-Trace Errors:

If you use axum::Form with the defaults turned off and the feature missing, the error might appear later as a trait bound failure on your handler, not just an import error. Always double-check Cargo.toml first when something related to form handling fails.

Common Beginner Mistakes with Form

  1. Wrong Content-Type: Sending a POST with application/json or no header at all. Axum expects application/x-www-form-urlencoded for Form. Use the correct header in curl or ensure your HTML form has no enctype (or enctype="application/x-www-form-urlencoded").
  2. Field name mismatch: The struct field username will not capture a form field named user_name. Serde is case-sensitive and name-exact. Rename fields with #[serde(rename = "user_name")] if needed.
  3. Trying to use Form for multipart/form-data: File uploads require Multipart. Form only handles URL-encoded data.
  4. Forgetting serde derive: Without #[derive(Deserialize)] or #[derive(Serialize)], serde cannot generate the conversion code, and the compiler will complain about missing trait implementations.
  5. Using Form with a raw HashMap<String, String>: This works, but you lose the type safety of a struct. It can be useful for quick prototypes, but for production code, define a struct.

Body Extractor Must Be Last:

In a handler with multiple extractors, Form consumes the request body (for non-GET methods). It must be the last extractor parameter. For example, async fn handler(Path(id): Path<u32>, Form(form): Form<LoginForm>) works, but async fn handler(Form(form): Form<LoginForm>, Path(id): Path<u32>) fails to compile - Axum only allows a body-consuming extractor as the last parameter. This rule applies to all body-consuming extractors like Json and Bytes.

Full Runnable Example with Multiple Routes

Here is a complete main.rs that combines all the examples above. You can copy this into your project, ensure your Cargo.toml has the required dependencies and features, and run it.

use axum::{
    routing::{get, post},
    Router,
    Form,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: Option<String>,
    #[serde(default)]
    remember_me: bool,
}
#[derive(Deserialize)]
struct SignupForm {
    username: String,
    city: String,
    country: String,
}
#[derive(Serialize)]
struct Payload {
    status: String,
    count: u32,
}
async fn login_handler(Form(input): Form<LoginForm>) -> String {
    let password_msg = match input.password {
        Some(p) => format!("password: {}", p),
        None => "no password provided".to_string(),
    };
    format!(
        "User: {} | {} | remember_me: {}",
        input.username, password_msg, input.remember_me
    )
}
async fn signup_handler(Form(input): Form<SignupForm>) -> String {
    format!(
        "{} lives in {}, {}",
        input.username, input.city, input.country
    )
}
async fn search_handler(Form(query): Form<LoginForm>) -> String {
    format!(
        "Searching for username: {} with password: {:?}",
        query.username, query.password
    )
}
async fn form_response_handler() -> Form<Payload> {
    Form(Payload {
        status: "ok".to_string(),
        count: 42,
    })
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/login", post(login_handler))
        .route("/signup", post(signup_handler))
        .route("/search", get(search_handler))
        .route("/payload", get(form_response_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Test each endpoint with curl:

# POST login
curl -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=alice&password=secret123&remember_me=true"
# POST signup
curl -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=alice&city=Berlin&country=Germany"
# GET search (query string)
curl "http://127.0.0.1:3000/search?username=bob&password=abc"
# GET form response
curl http://127.0.0.1:3000/payload

Each command produces a clear, expected response. Running all of them gives you confidence that the form feature is working correctly in both directions.

When to Use Form Instead of Query or Json

  • Use Query when you only need to read query string parameters from GET requests and want the data to appear in the URL.
  • Use Form when you are dealing with traditional HTML forms (either GET or POST) and the data is URL-encoded. Form gives you the same parsing but adapts to the HTTP method.
  • Use Json when the client sends data in JSON format (usually from a JavaScript frontend or API client). JSON bodies have a different content type and a different structure.

For a beginner, the best mental model is: if you see key=value&key2=value2 in the URL or body, use Form. If you see {"key": "value"} in the body, use Json.

Summary

The axum form feature unlocks the Form type, which handles application/x-www-form-urlencoded data. This is the format used by standard HTML forms. In axum 0.8 the feature is on by default, so a plain axum = "0.8" dependency already includes it - you only need to name it in Cargo.toml if you turned off the default features.

The Form extractor reads from the query string for GET requests and from the body for other methods, provided the correct Content-Type header is present. It requires a struct that derives Deserialize. You can also return Form<T> from a handler to send URL-encoded responses.

The most frequent errors are sending the wrong Content-Type, confusing Form with Multipart, and trying to deserialize nested structs from flat form data. With the examples on this page, you now have a solid foundation for accepting and returning form data in Axum.