application/x-www-form-urlencoded

Understand how Axum's Form extractor works with the application/x-www-form-urlencoded content type, the default encoding for HTML forms, and how to use it in your handlers.

When a browser submits a standard HTML form, it packages the form fields into a single string and sends it to the server. The HTTP header Content-Type announces how that string is formatted. For regular forms, that header is almost always application/x-www-form-urlencoded. Axum has a dedicated extractor called Form that understands this format and can turn it into a Rust struct automatically.

This page explains what that content type actually looks like on the wire, why it exists, how Axum parses it, and how you can use the Form extractor to receive and send this kind of data. The Form extractor lives behind Axum's form feature flag, but that flag is enabled by default, so a plain axum = "0.8" dependency already includes it. You only need to enable it explicitly if you disabled default features.

What Is application/x-www-form-urlencoded?

application/x-www-form-urlencoded is a MIME type that describes a simple text format for encoding key-value pairs. It has been used by HTML forms since the early days of the web. The encoding rules are straightforward:

  • Every form field becomes name=value.
  • Multiple fields are joined with an ampersand &.
  • Spaces become + or %20.
  • Special characters (like &, =, non-ASCII letters, etc.) are percent-encoded with their UTF-8 byte values, e.g. %26 for &.

For example, a form with fields username = "alice" and password = "s3cret!" becomes:

username=alice&password=s3cret%21

The exclamation mark ! is not strictly required to be percent-encoded, but it often is by browsers. Axum accepts both encoded and unencoded forms for characters that are allowed unencoded.

Why this format?:

This encoding was designed for sending data in the body of an HTTP request where the body is just a flat string. It is simple, widely supported, and works with every programming language. It is not well-suited for nested structures or binary data, but for simple form fields it remains the standard.

How HTML Forms Send Data

When you write an HTML form like this:

<form action="/signup" method="post">
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">Sign up</button>
</form>

and a user submits it, the browser performs an HTTP POST request to /signup with:

  • Content-Type: application/x-www-form-urlencoded
  • Body: username=whatever&password=whatever

The browser automatically encodes the fields using the rules above. Your Axum handler can then extract those fields using the Form extractor.

For GET requests, the same encoding appears in the URL query string (e.g., /signup?username=alice&password=s3cret). The Form extractor in Axum handles that case as well, but the Content-Type header is not involved because a GET request typically has no body. This page focuses on the POST body with that specific content type.

Enabling the Form Feature in Axum

Axum's Form extractor is gated behind the form feature flag, but that flag is enabled by default. If you are using Axum from crates.io with default features, you do not need to do anything. Only if you disabled default features must you add it back in your Cargo.toml:

[dependencies]
axum = { version = "0.8", features = ["form"] }
serde = { version = "1", features = ["derive"] }

If the form feature is off, you will see a compilation error like cannot find struct Form.

Basic Form Extraction with Axum

Let's build the simplest possible handler that receives an application/x-www-form-urlencoded body and converts it into a Rust struct.

We need a struct that derives serde::Deserialize. Each field name in the struct must match the name attribute of the corresponding form input.

use axum::Form;
use serde::Deserialize;
#[derive(Deserialize)]
struct SignUp {
    username: String,
    password: String,
}
async fn accept_form(Form(sign_up): Form<SignUp>) -> String {
    format!("User {} signed up!", sign_up.username)
}

The handler parameter Form(sign_up): Form<SignUp> does two things: it tells Axum to use the Form extractor, and it immediately destructures the inner value into the variable sign_up. The type inside Form is the struct that will be deserialized from the body.

Now we need to attach this handler to a route in a complete Axum application:

use axum::{routing::post, Router, Form};
use serde::Deserialize;
#[derive(Deserialize)]
struct SignUp {
    username: String,
    password: String,
}
async fn accept_form(Form(sign_up): Form<SignUp>) -> String {
    format!("User {} signed up!", sign_up.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/signup", post(accept_form));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Start this server and send a request with Content-Type: application/x-www-form-urlencoded and a body like username=alice&password=s3cret. The handler will return User alice signed up!.

The deserialization process uses the serde_urlencoded crate under the hood. It splits the body on &, then each piece on the first =, percent-decodes both sides, and then uses serde to map the keys to your struct fields.

It works when...:

If you see the response User alice signed up! in your terminal or browser, your Axum app is successfully parsing urlencoded form data.

Sending Requests with the Correct Content-Type

The Form extractor will only attempt to parse the body as urlencoded if the request method is not GET or HEAD and the Content-Type header is exactly application/x-www-form-urlencoded. If you send a POST with a JSON body, or with no Content-Type header at all, Axum rejects the request with 415 Unsupported Media Type. If the content type is right but the body does not match your struct, the rejection is a 422 Unprocessable Entity instead.

Here are several ways to send a valid request.

Using curl

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

The -d flag automatically sets Content-Type: application/x-www-form-urlencoded unless you override it. So you could omit the -H line.

Using JavaScript fetch

const response = await fetch("http://127.0.0.1:3000/signup", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: new URLSearchParams({
    username: "alice",
    password: "s3cret",
  }).toString(),
});

URLSearchParams produces the exact urlencoded string that the server expects.

Using an HTML form

The simplest way is to place an HTML form in a static file and let the browser handle the encoding. The browser will automatically set the correct content type when you use method="post".

<form action="http://127.0.0.1:3000/signup" method="post">
  <input name="username" type="text" />
  <input name="password" type="password" />
  <button type="submit">Sign up</button>
</form>

Submitting this form will produce exactly the request Axum expects.

Missing Content-Type leads to rejection:

If you send a POST request without a Content-Type header, many HTTP clients default to application/octet-stream or text/plain. Axum will not know it is urlencoded and will reject the extraction with an InvalidFormContentType rejection, resulting in a 415 Unsupported Media Type response. Always set the header explicitly when using a client that does not do it for you.

Working with Different Data Structures

A urlencoded body is flat by nature. It cannot represent nested objects or arrays like JSON can. However, you can still deserialize into many useful Rust types.

Struct with Optional Fields

If a form field is not always present, you can use Option<T>.

use axum::Form;
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
    query: String,
    page: Option<u32>,
}
async fn search(Form(params): Form<SearchParams>) -> String {
    let page = params.page.unwrap_or(1);
    format!("Searching for '{}' on page {}", params.query, page)
}

If the form only sends query=rust, the page field will be None. You can then provide a default.

Struct with Default Values

You can combine #[serde(default)] with Option or with a concrete default value.

#[derive(Deserialize)]
struct Preferences {
    theme: String,
    #[serde(default = "default_language")]
    language: String,
}
fn default_language() -> String {
    "en".to_string()
}

Now if the form omits language, it will default to "en".

HashMap for Dynamic Fields

Sometimes you don't know the field names ahead of time. You can deserialize into a HashMap<String, String>.

use axum::Form;
use std::collections::HashMap;
async fn handle_dynamic_form(Form(fields): Form<HashMap<String, String>>) -> String {
    let mut result = String::new();
    for (key, value) in &fields {
        result.push_str(&format!("{}={}\n", key, value));
    }
    result
}

Every key-value pair in the body becomes an entry in the map. If a key appears multiple times, the last value wins (serde_urlencoded behavior).

Vec of Tuples for Repeating Keys

If you need to preserve multiple values for the same key (e.g., checkboxes), you can deserialize into Vec<(String, String)>.

use axum::Form;
async fn handle_repeated_fields(Form(pairs): Form<Vec<(String, String)>>) -> String {
    let mut result = String::new();
    for (key, value) in pairs {
        result.push_str(&format!("{}: {}\n", key, value));
    }
    result
}

This works because serde_urlencoded supports deserializing a sequence of key-value pairs when the body contains repeated keys like tag=rust&tag=axum.

Handling Numeric and Boolean Types

Serde will convert strings from the form into the requested type as long as the string can be parsed. For example, u32 expects a string of digits. A boolean expects exactly "true" or "false" in lowercase; "TRUE" or "True" are rejected. If the string cannot be parsed, the extraction fails.

#[derive(Deserialize)]
struct Registration {
    age: u32,
    newsletter: bool,
}

A body like age=thirty&newsletter=yes would cause a deserialization error because "thirty" is not a valid u32 and "yes" is not a valid boolean.

Type mismatch causes rejection:

If you send age=twenty when the struct expects u32, Axum will return a FormRejection with a FailedToDeserializeFormBody error. This becomes a 422 Unprocessable Entity response for a POST body. Always ensure the client sends values that can be parsed into your types.

Handling Errors and Rejections

The Form extractor can fail for several reasons:

  • Missing Content-Type header (for non-GET/HEAD).
  • Incorrect Content-Type (e.g., application/json).
  • Body cannot be read (connection error).
  • Body string is not valid urlencoded (malformed percent-encoding).
  • Serde cannot map the fields to your struct (missing required field, type mismatch).
  • Body size exceeds the default limit (2 MB by default, like the Json extractor).

When the extractor fails, it returns a FormRejection. Axum converts this into an HTTP response automatically. The status code depends on the reason:

  • InvalidFormContentType -> 415 Unsupported Media Type
  • FailedToDeserializeForm -> 400 Bad Request (only for GET and HEAD requests, where Form reads the query string)
  • FailedToDeserializeFormBody -> 422 Unprocessable Entity (for POST and other methods, where Form reads the body)
  • BytesRejection (body read error) -> 413 Payload Too Large if the body exceeded the size limit, otherwise 500 Internal Server Error

You can handle these rejections manually if you want to customize the response. The simplest way is to use Result<Form<T>, FormRejection> as your handler parameter:

use axum::{Form, http::StatusCode};
use serde::Deserialize;
#[derive(Deserialize)]
struct Credentials {
    username: String,
    password: String,
}
async fn login(
    result: Result<Form<Credentials>, axum::extract::rejection::FormRejection>,
) -> Result<String, (StatusCode, String)> {
    match result {
        Ok(Form(creds)) => Ok(format!("Welcome {}", creds.username)),
        Err(rejection) => {
            let status = rejection.status();
            let message = format!("Form error: {}", rejection);
            Err((status, message))
        }
    }
}

However, keep in mind that FormRejection is not Clone, and the Display implementation may not give you the most user-friendly message. For production, you might want to map the rejection to a simple generic error message.

A cleaner approach for basic usage is to let Axum's default behavior handle the rejection and focus on successful parsing. Most beginners do not need to manually handle rejections until they build more complex APIs.

Using Form as a Response

The Form type can also be used as a response. Instead of extracting data from a request, it serializes your Rust struct into a urlencoded string and sets the response Content-Type to application/x-www-form-urlencoded.

To use it, your type must implement serde::Serialize.

use axum::Form;
use serde::Serialize;
#[derive(Serialize)]
struct Payload {
    message: String,
    id: u32,
}
async fn respond_with_form() -> Form<Payload> {
    Form(Payload {
        message: "Hello".to_string(),
        id: 42,
    })
}

Attach this to a route and call it. The response body will be something like:

message=Hello&id=42

And the response header will include Content-Type: application/x-www-form-urlencoded.

This is rarely used in modern APIs because JSON is more popular for responses, but it can be useful when you need to respond to a client that specifically expects urlencoded data.

Comparing with Other Content Types

It helps to understand where application/x-www-form-urlencoded fits in the ecosystem.

  • application/json - structured, supports nesting, arrays, and typed values. Used by most modern APIs. Axum's Json extractor handles it.
  • multipart/form-data - used for file uploads and forms with binary data. It encodes each field as a separate part with boundaries. Axum has a Multipart extractor (requires multipart feature). This content type is not handled by Form.
  • text/plain - raw text, no structured parsing. You would use String body extractor for that.

application/x-www-form-urlencoded remains the default for classic server-rendered HTML forms. If you are building a traditional web application with server-side rendering (like using templates), you will almost certainly use this content type for form submissions.

Form vs Query:

The Form extractor handles both GET query strings and non-GET urlencoded bodies. The Query extractor only handles query strings (the part after ? in the URL). They share the same deserialization logic because the encoding is identical, but the source is different: Form reads from the body for POST, PUT, etc., while Query always reads from the URL. This page focuses on Form with the body.

Common Pitfalls and Solutions

Let's list the mistakes beginners often make when working with urlencoded forms.

1. Forgetting the form feature

Symptom: Compilation error: cannot find struct Form.

Fix: This only happens if you disabled Axum's default features. Add features = ["form"] to your axum dependency in Cargo.toml. With default features on, form is already enabled.

2. Not setting the Content-Type header

Symptom: Request returns 415 Unsupported Media Type.

Fix: Ensure your client sends Content-Type: application/x-www-form-urlencoded. If using curl, the -d flag does this automatically. If using fetch, you must set it manually unless you use URLSearchParams directly as the body (which sets the header automatically in modern browsers, but it's safer to set it explicitly).

3. Field name mismatch

Symptom: Request returns 422 Unprocessable Entity with "missing field username" (for a POST body; the same failure on a GET query string returns 400 Bad Request).

Fix: Check that the name attributes in your HTML form exactly match the Rust struct field names (case-sensitive). You can also use serde attributes to rename fields:

#[derive(Deserialize)]
struct User {
    #[serde(rename = "user_name")]
    username: String,
}

4. Expecting nested data

Symptom: Client sends JSON-like nested structure, but urlencoded doesn't support it.

Fix: Flatten your data. Instead of sending a nested object, use separate top-level fields with a naming convention like address_city=Berlin&address_zip=10115, and define matching fields in your struct. Dot notation like address.city=Berlin does not create nesting: serde_urlencoded treats it as a literal key, so no struct field matches it.

5. Large payloads and body size limit

Symptom: Request returns 413 Payload Too Large when sending a lot of data.

Fix: The default body limit for extractors is 2 MB. If your forms can exceed that, you need to change the limit using the DefaultBodyLimit layer. For most login and signup forms, 2 MB is more than enough.

6. Mixed & and = in values

If a form value contains a literal & or =, it must be percent-encoded (e.g., %26 for &). Browsers do this automatically, but if you craft a body manually, remember to encode those characters. The parser is lenient about the shape: it splits each pair on the first =, so an = inside a value is fine, a stray & is ignored, and even a bad escape like %ZZ passes through instead of failing. What breaks is the meaning, not the parse: an unencoded & silently splits one value into two pairs, so the server receives different fields than you intended.

Always let the client encode:

If you are building the body string yourself (not using URLSearchParams or a browser form), use a proper urlencoding library or function. Manual string concatenation often leads to invalid encoding and hard-to-find bugs.

A Complete End-to-End Example

Let's put everything together in a single runnable application that shows both extracting a form and responding with a form.

Step 1: Create a new Rust project

cargo new axum_form_demo
cd axum_form_demo

Step 2: Add dependencies in Cargo.toml

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

Step 3: Write the main code in src/main.rs

use axum::{
    extract::rejection::FormRejection,
    routing::{get, post},
    Form, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Deserialize)]
struct ContactForm {
    name: String,
    email: String,
    message: String,
}
#[derive(Serialize)]
struct Ack {
    status: String,
    id: u32,
}
async fn submit_contact(
    form_result: Result<Form<ContactForm>, FormRejection>,
) -> Result<Form<Ack>, (axum::http::StatusCode, String)> {
    match form_result {
        Ok(Form(contact)) => {
            println!(
                "Received message from {} ({})",
                contact.name, contact.email
            );
            let ack = Ack {
                status: "success".to_string(),
                id: 123,
            };
            Ok(Form(ack))
        }
        Err(rejection) => {
            let status = rejection.status();
            let msg = format!("Form error: {}", rejection);
            Err((status, msg))
        }
    }
}
async fn show_form() -> axum::response::Html<&'static str> {
    axum::response::Html(
        r#"
        <!DOCTYPE html>
        <html>
        <head><title>Contact</title></head>
        <body>
            <form action="/submit" method="post">
                <input name="name" placeholder="Name" /><br>
                <input name="email" placeholder="Email" /><br>
                <textarea name="message" placeholder="Message"></textarea><br>
                <button type="submit">Send</button>
            </form>
        </body>
        </html>
        "#,
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(show_form))
        .route("/submit", post(submit_contact));
    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();
}

This example includes:

  • A GET / route that shows a basic HTML form.
  • A POST /submit route that extracts the form data.
  • Manual rejection handling to show how to catch errors.
  • A Form<Ack> response that returns a urlencoded body. The browser will display the raw response like status=success&id=123.

You can test it by visiting http://127.0.0.1:3000 in a browser, filling in the form, and submitting. You will see the server log the fields, and the response will be the urlencoded acknowledgment.

Everything works:

When you submit the form and see the urlencoded response status=success&id=123, you have successfully used application/x-www-form-urlencoded both ways in Axum.

The Mechanics Under the Hood

Understanding how Axum and serde_urlencoded cooperate helps you debug problems more effectively. The sequence is:

  1. The request arrives with a body and a Content-Type header.
  2. Axum's Form extractor checks the method. If it is GET or HEAD, it skips the body and looks at the URI query string. Otherwise, it reads the Content-Type header and verifies it is application/x-www-form-urlencoded. If not, it returns a rejection.
  3. The extractor reads the entire body into memory as bytes (respecting the body size limit).
  4. Those bytes are converted to a string (expected to be valid UTF-8).
  5. The string is parsed using serde_urlencoded into a generic map of key-value pairs.
  6. Serde then deserializes that map into your target type T. This involves matching field names, converting string values to the expected types, and applying any #[serde] attributes.
  7. If any step fails, a rejection is returned. Otherwise, the value is passed to your handler.

This entire process happens before your handler function is called. You never have to manually parse the body.

Final Thoughts

application/x-www-form-urlencoded is a fundamental format for web forms. Axum's Form extractor makes working with it remarkably simple: define a struct that implements Deserialize, and put Form<YourStruct> in your handler parameters. The extractor handles all the parsing, content-type checks, and error reporting.

The most important things to remember are:

  • The form feature is enabled by default in Axum; only re-enable it if you turned default features off.
  • Ensure the client sends the correct Content-Type header for POST requests.
  • Match your struct field names to the form input names (or use #[serde(rename)]).
  • The body must be flat key-value pairs; use HashMap or Vec<(String, String)> for dynamic or repeated fields.

The single idea that ties the format together is that the content type decides everything. The same flat string in the body is a form submission when the header says application/x-www-form-urlencoded, and the same string after a ? is a query string when there is no body at all. That is why the three failure modes have different statuses: a wrong header is a 415, a body that does not match your struct is a 422, and the same mismatch in a query string is a 400. If you read the status first, you know whether to fix the client, the struct, or the route, before you touch any other code.