Axum as request handling library

Learn how Axum processes incoming HTTP requests through handlers, extractors, responses, and its predictable error model

Axum as request handling library

Axum is often described as an HTTP routing and request-handling library. The routing part is covered elsewhere; this page focuses on the request-handling side. That means understanding what happens after a route is matched: how Axum takes the raw HTTP request, helps you pull out the data you need, calls your application logic, and turns the result back into an HTTP response. If you have ever used a web framework in another language, you can think of this as the "controller" layer - but Axum's approach is built entirely on plain Rust functions and the type system.

Before going further, this page assumes you know what an HTTP request and response look like: a request has a method, a path, headers, and possibly a body, and a response has a status code, headers, and a body.

The core unit: handlers

In Axum, a handler is just an async function that accepts zero or more extractors and returns something that can be converted into an HTTP response. There is no special annotation, no macro, no base class to inherit. Any async function that meets these requirements can be used as a handler.

Let's start with the absolute minimum:

use axum::{
    routing::get,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello_world));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn hello_world() -> &'static str {
    "Hello, World!"
}

When a request arrives for GET /, Axum calls hello_world, takes the string it returns, and builds an HTTP response with status 200 OK, a Content-Type of text/plain, and the string as the body. The handler does not need to know anything about HTTP internals; Axum does that conversion for you.

You can also return a String, which works the same way because both &'static str and String implement the IntoResponse trait. That trait is the contract that says "this type can become an HTTP response." Axum provides implementations for many common Rust types, so you rarely need to build a raw response yourself.

Everything working:

If you run the example above and visit http://localhost:3000 in your browser, you should see "Hello, World!" on a blank page. That confirms the handler returned successfully and Axum sent back a valid response.

Extracting data from the request

Most real handlers need information from the incoming request: a path segment, a query parameter, JSON in the body, a header, or something else. In Axum, you get these by declaring extractor parameters in your handler's signature. An extractor is a type that implements FromRequest (or FromRequestParts) and knows how to pull a specific piece of data out of the request.

Here is a handler that extracts a path parameter:

use axum::{
    extract::Path,
    routing::get,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn get_user(Path(user_id): Path<u64>) -> String {
    format!("User ID: {}", user_id)
}

Notice the handler signature: async fn get_user(Path(user_id): Path<u64>) -> String. The argument Path<u64> tells Axum "extract the {id} path parameter and parse it as a u64." If the value cannot be parsed (for example, a request to /users/abc), Axum automatically returns a 400 Bad Request response without ever calling your handler. This compile-time type safety is a core part of Axum's ergonomics.

You can combine multiple extractors. The order matters in one special case: at most one extractor may consume the request body (like Json, Form, or Bytes), and it must be the last argument. Other extractors (like Path, Query, HeaderMap, State) can appear in any order before it.

Here is a handler that takes a path parameter, a query string, and a JSON body:

use axum::{
    extract::{Path, Query, Json},
    routing::post,
    Router,
};
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Deserialize)]
struct CreateUser {
    name: String,
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{id}", post(update_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn update_user(
    Path(id): Path<u64>,
    Query(params): Query<HashMap<String, String>>,
    Json(payload): Json<CreateUser>,
) -> String {
    format!(
        "Updating user {} with name {} and params {:?}",
        id, payload.name, params
    )
}

When a client sends POST /users/42?notify=true with a JSON body {"name": "Alice"}, Axum will parse all three extractors and pass the values to your handler. If any extractor fails - for example, the JSON is malformed - Axum returns a 400 Bad Request or 422 Unprocessable Entity (depending on the extractor) before your handler runs.

Body-consuming extractor placement:

Only one extractor may consume the request body. If you try to use two body extractors, like Json and Form together, the compiler will reject it. Also, the body-consuming extractor must be the last argument in the handler signature. Placing it earlier will cause a compile-time error.

Returning responses

Axum's handler return type must implement IntoResponse. That trait converts your return value into an HTTP response with a status code, headers, and body. Many types already implement it: strings, StatusCode, tuples of (StatusCode, T) where T implements IntoResponse, Json<T>, Html<T>, Result<T, E> where both T and E implement IntoResponse, and more.

The simplest response is a string, which becomes 200 OK with text/plain. To control the status code, you can return a tuple:

use axum::{
    http::StatusCode,
    routing::get,
    Router,
};
async fn create_user() -> (StatusCode, &'static str) {
    (StatusCode::CREATED, "User created")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", axum::routing::post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here the handler returns a tuple with 201 Created and a plain text body. Tuples up to a certain size are implemented for common combinations, so (StatusCode, Json<T>), (StatusCode, HeaderMap, String), and many others work out of the box.

For JSON APIs, wrap your data in Json:

use axum::{Json, routing::get, Router};
use serde::Serialize;
#[derive(Serialize)]
struct User {
    id: u64,
    name: String,
}
async fn get_user() -> Json<User> {
    Json(User {
        id: 1,
        name: "Alice".to_string(),
    })
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/user", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Json<T> automatically sets Content-Type: application/json and serializes the value using serde.

You can also implement IntoResponse for your own custom type to have full control over the response. This is useful for building a unified API response format:

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;
#[derive(Serialize)]
struct ApiError {
    error: String,
}
enum ApiResponse<T> {
    Ok(T),
    Created(T),
    NotFound(String),
}
impl<T: Serialize> IntoResponse for ApiResponse<T> {
    fn into_response(self) -> Response {
        match self {
            ApiResponse::Ok(data) => (StatusCode::OK, Json(data)).into_response(),
            ApiResponse::Created(data) => (StatusCode::CREATED, Json(data)).into_response(),
            ApiResponse::NotFound(message) => {
                (StatusCode::NOT_FOUND, Json(ApiError { error: message })).into_response()
            }
        }
    }
}
// Usage in a handler:
async fn get_user() -> ApiResponse<User> {
    // ... fetch user ...
    ApiResponse::Ok(User { id: 1, name: "Alice".into() })
}

This pattern lets you keep handlers clean and centralize response formatting.

Error handling model

Axum's error handling is simple and predictable. If your handler returns a Result<T, E> where both T and E implement IntoResponse, Axum will convert the Ok variant or the Err variant into a response. This is the recommended way to handle domain errors without writing match statements everywhere.

A minimal example with real inputs:

use axum::{
    extract::Query,
    http::StatusCode,
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct DivideParams {
    a: u64,
    b: u64,
}
async fn divide(Query(params): Query<DivideParams>) -> Result<String, StatusCode> {
    if params.b == 0 {
        return Err(StatusCode::BAD_REQUEST);
    }
    Ok(format!("{}", params.a / params.b))
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/divide", get(divide));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here the two numbers come from the query string (/divide?a=10&b=2 gives 5), and a zero divisor becomes a 400 Bad Request response. The Query extractor is what turns the ?a=10&b=2 part of the URL into the DivideParams struct - a bare u64 parameter would not compile, because every handler argument must be an extractor.

Here is a more realistic handler using a custom error type:

use axum::{
    extract::Path,
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;
#[derive(Serialize)]
struct User {
    id: u64,
    name: String,
}
#[derive(Debug)]
enum AppError {
    NotFound,
    Unauthorized,
    DatabaseError(String),
}
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "Resource not found".to_string()),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Not authorized".to_string()),
            AppError::DatabaseError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg),
        };
        (status, Json(serde_json::json!({ "error": message }))).into_response()
    }
}
async fn get_user(Path(id): Path<u64>) -> Result<Json<User>, AppError> {
    if id == 0 {
        Err(AppError::NotFound)
    } else {
        Ok(Json(User { id, name: "Alice".into() }))
    }
}

Because both Json<User> and AppError implement IntoResponse, the Result automatically becomes a valid response. When an error occurs, Axum returns the error response with the appropriate status and JSON body.

Panics do not become 500 by default:

If your handler returns a Result and the error type does not implement IntoResponse, the code will not compile. If an extractor fails (for example, a path parameter cannot be parsed), Axum automatically returns a 400 or 422 response, so you don't need to handle those yourself. However, any unexpected error inside your handler that you propagate as a Result::Err with a type that does implement IntoResponse will be sent as that response. If you panic, Axum does not turn it into a 500 by default - the connection is dropped with no response. To get a 500 from a panic, add tower_http::catch_panic::CatchPanicLayer (see "Panicking inside a handler" in Common mistakes below).

Body size limits and the Json Content-Type rule

Two request-handling defaults catch beginners out. First, bodies are size-limited: extractors built on Bytes - Bytes itself, String, Json, and Form - refuse bodies larger than 2 MB by default (the rejection is 413 Payload Too Large). Change the limit with the DefaultBodyLimit layer, applied to the whole router or to a single route:

use axum::{extract::DefaultBodyLimit, routing::post, Router};

async fn upload(body: axum::body::Bytes) -> String {
    format!("Received {} bytes", body.len())
}

// Allow JSON bodies up to 10 MB on every route.
let app = Router::new()
    .route("/upload", post(upload))
    .layer(DefaultBodyLimit::max(10 * 1024 * 1024));

// Or remove the limit entirely for one route (pair it with a
// tower_http::limit::RequestBodyLimitLayer if the client is untrusted).
let _app_unlimited = Router::new()
    .route("/upload", post(upload).layer(DefaultBodyLimit::disable()));

Second, the Json extractor checks the request's Content-Type before it looks at the body at all. A POST with a JSON body but no Content-Type: application/json header - or the wrong content type - is rejected with 415 Unsupported Media Type, even if the bytes are valid JSON. Malformed JSON is 400 Bad Request, and JSON that parses but has the wrong shape (for example a missing field) is 422 Unprocessable Entity.

Putting it together: a small in-memory API

Now we'll build a tiny but complete example that demonstrates handlers, extractors, responses, state, and error handling working together. This will be an in-memory todo list API with three endpoints: create a todo, list todos, and delete a todo by ID. We'll use shared state via Arc<Mutex<Vec<Todo>>> to keep it simple.

We'll walk through this step by step with a Stepper, because each step depends on the previous one.

1

Step 1: Define the data structures and shared state

First, create a Todo struct and a CreateTodo struct for input. We'll also define a type alias for our shared state.

// src/main.rs
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};
#[derive(Clone, Serialize)]
struct Todo {
    id: u64,
    text: String,
    done: bool,
}
#[derive(Deserialize)]
struct CreateTodo {
    text: String,
}
type SharedState = Arc<Mutex<HashMap<u64, Todo>>>;
fn new_shared_state() -> SharedState {
    Arc::new(Mutex::new(HashMap::new()))
}
2

Step 2: Write the handlers

Create three handlers: create_todo, list_todos, and delete_todo. They use State to access the shared map and Json/Path extractors.

async fn create_todo(
    State(state): State<SharedState>,
    Json(payload): Json<CreateTodo>,
) -> impl IntoResponse {
    let mut map = state.lock().unwrap();
    let id = map.len() as u64 + 1;
    let todo = Todo {
        id,
        text: payload.text,
        done: false,
    };
    map.insert(id, todo.clone());
    (StatusCode::CREATED, Json(todo))
}
async fn list_todos(State(state): State<SharedState>) -> Json<Vec<Todo>> {
    let map = state.lock().unwrap();
    let mut todos: Vec<_> = map.values().cloned().collect();
    todos.sort_by_key(|t| t.id);
    Json(todos)
}
async fn delete_todo(
    State(state): State<SharedState>,
    Path(id): Path<u64>,
) -> Response {
    let mut map = state.lock().unwrap();
    if map.remove(&id).is_some() {
        StatusCode::NO_CONTENT.into_response()
    } else {
        (StatusCode::NOT_FOUND, "Todo not found").into_response()
    }
}
3

Step 3: Build the router and provide state

Construct a Router, add routes, and attach the shared state using .with_state().

fn app() -> Router {
    Router::new()
        .route("/todos", post(create_todo).get(list_todos))
        .route("/todos/{id}", axum::routing::delete(delete_todo))
        .with_state(new_shared_state())
}
4

Step 4: Start the server

Finally, bind a TCP listener and serve the app.

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Listening on http://localhost:3000");
    axum::serve(listener, app()).await.unwrap();
}

You can test this API with curl:

# Create a todo
curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"text":"Learn Axum"}'
# List todos
curl http://localhost:3000/todos
# Delete a todo (replace 1 with actual ID)
curl -X DELETE http://localhost:3000/todos/1

The first request returns 201 Created with the new todo as JSON. The second returns a JSON array. The third returns 204 No Content on success or 404 Not Found if the ID doesn't exist.

State and concurrency:

Because multiple requests can arrive at the same time, we use Arc<Mutex<...>> to safely share and mutate the map across tasks. In a real application you would likely use a database instead of an in-memory map, but this pattern shows how Axum's State extractor gives each handler access to shared data.

Common mistakes and how to avoid them

Beginners often run into a few recurring issues when writing Axum handlers. Knowing them in advance can save hours of debugging.

Forgetting to extract the inner value from an extractor. Extractors like Json, Path, and Query are wrapper types. You must destructure them in the function parameter: Json(payload): Json<MyType> gives you payload of type MyType. If you write payload: Json<MyType>, you get the wrapper and must call .0 to access the value. The destructuring pattern is idiomatic and keeps the handler clean.

Mixing up path parameter syntax. Axum 0.8 changed from :param to {param}. Older tutorials may still show the colon syntax, which will not work - registering a route with it panics at startup in Axum 0.8. Always use {...} for path parameters.

Attempting to use multiple body extractors. A handler can only have one argument that consumes the request body. If you need both Json and Form from the same request, you'll have to write a custom extractor that reads the body once and parses it as needed. This is a deliberate design to avoid ambiguous consumption of the body.

Ignoring the return type requirements. Every handler must return something that implements IntoResponse. If you return a custom type that doesn't implement IntoResponse, the compiler will complain. The easiest fix is to implement IntoResponse for your custom type or convert it to a known response type (like Json or (StatusCode, String)) before returning.

Panicking inside a handler. Axum does not catch panics by default: a panic unwinds the task handling that request and the connection is dropped with no response sent to the client. (The server itself keeps running - only that request's task aborts.) If you want panics turned into 500 Internal Server Error responses, add tower_http::catch_panic::CatchPanicLayer - it needs the catch-panic feature of tower-http:

use tower_http::catch_panic::CatchPanicLayer;

let app = Router::new()
    .route("/", get(hello_world))
    .layer(CatchPanicLayer::new());

Even with that layer, it is better to handle errors gracefully. Return a Result with an appropriate error type or convert expected failures into a StatusCode response. Panics should be reserved for truly unexpected bugs.

Beware of silent failures:

If you use unwrap() on a Mutex lock and it gets poisoned (because another thread panicked while holding the lock), your handler will panic too, and the client gets no response at all (unless you added CatchPanicLayer, which turns it into a 500). Prefer lock().unwrap_or_else(|e| e.into_inner()) or use tokio::sync::Mutex with .lock().await in async contexts to avoid blocking.

Summary

Axum's request-handling model is built around three ideas: handlers are plain async functions, extractors pull data from the request using types, and IntoResponse turns your return value into an HTTP response. This composition makes request handling feel less like boilerplate and more like writing ordinary Rust functions with typed inputs and outputs.

The most important insight is that Axum leverages Rust's type system to catch many mistakes at compile time. A handler that uses the wrong type for an extractor, or returns an incompatible response type, will fail to compile rather than failing at runtime. But that compile-time checking has a limit: the compiler does not check path-parameter names against the route string. A handler that extracts Path<Params> where Params is a struct with a field named id, on a route written /users/{user_id}, compiles fine and fails at runtime with a rejection response instead. That means you spend less time writing validation logic and more time on your actual application - but route strings still deserve a careful look.

You should now be able to write handlers that accept data, return responses, and handle errors predictably - the foundation of every Axum application.