Actix-web vs Axum Extractor Style

Compares how Actix-web and Axum extract data from HTTP requests and pass it to handler functions, including path parameters, query strings, JSON bodies, and custom extractors.

When a web request arrives at your server, the raw HTTP data looks like a wall of text: method, headers, path, query parameters, and a body. A framework's job is to turn that wall into something your functions can actually use. Extractors are the mechanism that does this conversion. They take the raw request and pull out the pieces you care about - a path segment, a query value, a JSON payload - as properly typed Rust values.

This page compares how Actix-web and Axum handle extractors. Both achieve the same goal, but their styles differ in how much ceremony you write, how type errors surface, and how extraction failures are reported. We'll start with a simple example, then expand to more complex scenarios.

A First Look: Extracting a Path Parameter

Imagine a route like GET /users/42 where 42 is a user ID. The framework must capture 42 from the URL, parse it into a number, and hand it to your handler as an integer. Here's how each framework does it.

Axum Version (0.8)

A complete runnable Axum program that handles GET /users/{id}:

// src/main.rs
use axum::{routing::get, Router, extract::Path};
async fn get_user(Path(id): Path<u64>) -> String {
    format!("User ID: {id}")
}
#[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();
    println!("Listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

In the handler get_user, the parameter Path(id): Path<u64> is an extractor. Axum sees this and knows: "This function needs a path parameter, deserialized as a u64." It will look at the route pattern /users/{id}, capture the segment, try to parse it as u64, and pass it to the function. If the URL is /users/abc, parsing fails and Axum rejects the request with a 400 Bad Request automatically - you didn't write any error handling code.

Actix-web Version (4.x)

The equivalent Actix-web program:

// src/main.rs
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/users/{id}")]
async fn get_user(id: web::Path<u64>) -> impl Responder {
    format!("User ID: {}", id.into_inner())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_user)
    })
    .bind("127.0.0.1:3000")?
    .run()
    .await
}

Here the route is defined with the #[get("/users/{id}")] attribute macro, and the handler's parameter is web::Path<u64>. Actix-web also knows to capture {id} from the URL, parse it as u64, and pass it to the function. On failure (e.g., abc), Actix-web returns a 400 Bad Request as well, because web::Path implements FromRequest and its error type maps to that status code.

What's already visible: Axum's handler signature is shorter - just Path<u64> - while Actix-web requires the web:: prefix. This is a stylistic difference, not a functional one. Both frameworks rely on Rust's type system to know what to extract, but Axum's extractors are imported directly from axum::extract, while Actix-web groups them under the web module.

Extractor = a type that implements a trait:

In both frameworks, an extractor is any Rust type that implements a special trait (Axum's FromRequest or FromRequestParts, Actix-web's FromRequest). The framework calls that trait method to pull data from the request. You can write your own custom extractors by implementing these traits - we'll see how later.

How the Styles Differ: Inference vs. Explicit Naming

Axum's approach is often described as type-driven. You write types in your handler signature, and Axum figures out how to satisfy them. There are no route macros to connect the route pattern to the handler - the connection is made when you register the route with .route().

Actix-web's approach is also type-driven, but it feels more explicit because:

  • Routes are usually declared with attribute macros (#[get(...)], #[post(...)]) that contain the path.
  • Extractor types are always namespaced with web:: (e.g., web::Path, web::Query, web::Json).
  • You often need to call .into_inner() to get the inner value from a web::Path<T> or web::Json<T>.

This doesn't make Actix-web less type-safe; it just requires more visible typing. For a beginner, Axum's style may look cleaner because the handler signature reads like a wishlist of what you want, and the framework does the rest.

Same Example, Side-by-Side (Handler Only)

Axum:

async fn get_user(Path(id): Path<u64>) -> String {
    format!("User ID: {id}")
}

Actix-web:

async fn get_user(id: web::Path<u64>) -> impl Responder {
    format!("User ID: {}", id.into_inner())
}

Notice the pattern: Axum destructures Path(id) directly; Actix-web gives you the whole web::Path<u64> and you call into_inner() to get the u64. For simple cases, Axum feels lighter.

Extracting Query Parameters

Query parameters appear after ? in a URL, like /search?page=2&limit=20. Both frameworks use serde to deserialize them into a struct.

Axum: Query<T>

// src/main.rs
use axum::{routing::get, Router, extract::Query};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    limit: Option<u32>,
}
async fn list_items(Query(params): Query<Pagination>) -> String {
    let page = params.page.unwrap_or(1);
    let limit = params.limit.unwrap_or(20);
    format!("Page {page}, {limit} items")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/items", get(list_items));
    // ... serve
}

Call GET /items?page=2&limit=50 and the handler prints Page 2, 50 items. Missing parameters result in None because the struct fields are Option<u32>.

Actix-web: web::Query<T>

// src/main.rs
use actix_web::{get, web, App, HttpServer, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    limit: Option<u32>,
}
#[get("/items")]
async fn list_items(query: web::Query<Pagination>) -> impl Responder {
    let page = query.page.unwrap_or(1);
    let limit = query.limit.unwrap_or(20);
    format!("Page {page}, {limit} items")
}

In Actix-web, you can access fields directly on query because web::Query<T> implements Deref to T, so query.page works without calling into_inner(). This is one place where Actix-web is actually more ergonomic than Axum, which requires destructuring Query(params) first.

Forgot to derive Deserialize?:

Both frameworks depend on serde. If you forget #[derive(Deserialize)] on your struct, the code won't compile. The compiler error will mention that the trait Deserialize<'_> is not implemented. Always add that derive when using Query, Json, or Form extractors.

Extracting JSON Bodies

JSON bodies are common in REST APIs. Both frameworks use serde_json and require the target type to implement Deserialize.

Axum: Json<T>

use axum::{routing::post, Router, Json};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
async fn create_user(Json(payload): Json<CreateUser>) -> String {
    format!("Created {} ({})", payload.name, payload.email)
}

If the incoming JSON cannot be used, Axum automatically rejects the request - but not always with the same status. The Json extractor fails in three different ways, and each one gets its own status code (see axum::extract::rejection::JsonRejection):

  • Malformed JSON syntax (for example, an unclosed brace) → 400 Bad Request (JsonSyntaxError).
  • Well-formed JSON with the wrong shape (for example, a missing required field or a wrong type) → 422 Unprocessable Entity (JsonDataError), with a plain-text body.
  • Missing or wrong Content-Type (anything other than application/json) → 415 Unsupported Media Type (MissingJsonContentType).

You don't write any error handling for the default behavior - but if you want to customize the response, you need to know which of the three failures you are handling (see the error-handling section below).

Actix-web: web::Json<T>

use actix_web::{post, web, HttpResponse, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
#[post("/users")]
async fn create_user(payload: web::Json<CreateUser>) -> impl Responder {
    let user = payload.into_inner();
    HttpResponse::Created().body(format!("Created {} ({})", user.name, user.email))
}

Actix-web also rejects invalid JSON with 400 Bad Request by default, but the error body format is different. To customize error responses, you often need to implement ResponseError or use a custom extractor wrapper. Axum's rejection system is more uniform because every rejection can be turned into a response via IntoResponse.

Combining Multiple Extractors

Often a single handler needs data from several sources: a path ID, query filters, and a JSON body. Both frameworks allow multiple extractors in the parameter list, but there is an important rule.

The Body-Consuming Extractor Must Be Last

An HTTP request body can only be read once. If an extractor consumes the body (e.g., Json, Form, Bytes, String), no later extractor can read it. Both frameworks expect body-consuming extractors to be the last parameter. If you break this rule, you'll get a compile-time error in Axum, and a runtime panic or error in Actix-web.

Axum Example

use axum::{
    extract::{Path, Query, State},
    routing::post,
    Router, Json,
};
use serde::Deserialize;
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    db: String, // pretend database connection
}
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
#[derive(Deserialize)]
struct UpdateUser {
    name: String,
}
async fn update_user(
    State(state): State<Arc<AppState>>,
    Path(id): Path<u64>,
    Query(pagination): Query<Pagination>,
    Json(body): Json<UpdateUser>,
) -> String {
    format!(
        "DB={}, Update user {id} to {}, page={:?}",
        state.db,
        body.name,
        pagination.page.unwrap_or(1)
    )
}

In Axum, the compiler enforces that only one extractor implements FromRequest (body-consuming), and it must be last. If you place Json before Path, you get a compile error.

Actix-web Example

use actix_web::{post, web, HttpResponse, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
#[derive(Deserialize)]
struct UpdateUser {
    name: String,
}
#[post("/users/{id}")]
async fn update_user(
    id: web::Path<u64>,
    query: web::Query<Pagination>,
    body: web::Json<UpdateUser>,
) -> impl Responder {
    let user = body.into_inner();
    let id = id.into_inner();
    let page = query.page.unwrap_or(1);
    HttpResponse::Ok().body(format!("Update user {id} to {} (page {page})", user.name))
}

Actix-web does not enforce the order at compile time, so the order is yours to get right. The rule to remember is which extractors read the body and which do not. web::Query and web::Path read the request URI and the route match information, not the body, so putting web::Json before them works fine - the query string and the path are still there when their turn comes. The real trap is using two body-consuming extractors in one handler, for example web::Json followed by another web::Json, or web::Json followed by web::Bytes: the first one drains the request body, and the second one finds nothing left to read.

Two body extractors is the real ordering mistake:

In Actix-web, a body-consuming extractor (like web::Json) placed before another body-consuming extractor can lead to confusing runtime errors, because the body stream can only be read once. web::Query and web::Path are safe anywhere in the list - they read the URI, not the body. Axum's compile-time checks prevent the two-body-extractor mistake entirely. When in doubt, put body-consuming extractors last, and never use two of them.

Custom Extractors

Sometimes you need to extract something that isn't built-in - say, a specific header or an authentication token. Both frameworks let you define your own extractor types by implementing their trait.

Axum: Implementing FromRequestParts

Axum splits the trait into FromRequestParts (for data available before the body) and FromRequest (for body-consuming extractors). For a header, you'd implement FromRequestParts.

use axum::{
    async_trait,
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
};
use std::convert::Infallible;
// A custom extractor that reads the `x-request-id` header
pub struct RequestId(pub String);
#[async_trait]
impl<S> FromRequestParts<S> for RequestId
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if let Some(value) = parts.headers.get("x-request-id") {
            if let Ok(id) = value.to_str() {
                return Ok(RequestId(id.to_string()));
            }
        }
        Err((StatusCode::BAD_REQUEST, "missing x-request-id header"))
    }
}
// Usage in a handler
async fn handler(RequestId(id): RequestId) -> String {
    format!("Request ID: {id}")
}

Axum requires an async trait implementation because from_request_parts is async. The Rejection type defines what happens on failure - it must implement IntoResponse. This gives you full control over error responses.

Actix-web: Implementing FromRequest

Actix-web uses a single FromRequest trait with a method that receives both the request and the payload.

use actix_web::{
    dev::Payload, error::ErrorBadRequest, Error, FromRequest, HttpRequest,
};
use std::future::{ready, Ready};
pub struct RequestId(pub String);
impl FromRequest for RequestId {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;
    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        match req.headers().get("x-request-id") {
            Some(value) => match value.to_str() {
                Ok(id) => ready(Ok(RequestId(id.to_string()))),
                Err(_) => ready(Err(ErrorBadRequest("invalid header value"))),
            },
            None => ready(Err(ErrorBadRequest("missing x-request-id header"))),
        }
    }
}
// Usage
async fn handler(id: RequestId) -> impl Responder {
    format!("Request ID: {}", id.0)
}

Actix-web's trait is synchronous in implementation (though it returns a future), and you use ready() to wrap immediate results. The Error type is Actix's error type, which implements ResponseError, so returning it from an extractor automatically maps to an HTTP response.

Comparing complexity: Axum's split traits feel more granular but also more explicit about what part of the request you're working with. Actix-web's single trait is simpler in signature but forces you to think about the payload even when you don't need it (you can ignore it by using _payload). For a beginner, Axum's version may be easier to understand because the rejection type is just an IntoResponse, not a framework-specific error enum.

Custom extractors are a sign of mastery:

Being able to write your own extractor is a strong signal that you understand how the framework works. Both Axum and Actix-web make it possible, but Axum's separation of FromRequestParts and FromRequest encourages cleaner design. If you're just starting out, you don't need custom extractors - the built-in ones cover the common cases.

Error Handling Differences

When extraction fails (invalid path parameter, missing query field, malformed JSON), how does the framework tell the client?

Axum's Rejection System

Axum extractors return a Rejection type that implements IntoResponse. If you don't handle the rejection in your handler (by using ? or matching), Axum automatically converts it to an HTTP response. The default rejection for most extractors is 400 Bad Request with a text body explaining the error - except for Json, which splits failures into 400 (malformed syntax), 422 (wrong shape), and 415 (wrong or missing Content-Type), as shown above.

You can customize the response, but not with a global handler. HandleErrorLayer (from axum::error_handling) only handles errors produced by services and layers - for example, a TimeoutLayer that fails with a BoxError. It never sees extractor rejections, because an extractor turns its own failure into a finished HTTP response before any service error exists to handle: the handler service returns that response normally, so no error ever reaches the layer. There is no global extractor-rejection handler in Axum. Instead, you handle rejections in one of two places:

Per handler - return Result<Json<T>, JsonRejection> and match on it:

use axum::{
    extract::{rejection::JsonRejection, Json},
    http::StatusCode,
    response::{IntoResponse, Response},
};
async fn create_user(
    payload: Result<Json<CreateUser>, JsonRejection>,
) -> Response {
    match payload {
        Ok(Json(user)) => {
            (StatusCode::CREATED, format!("Created {}", user.name)).into_response()
        }
        Err(JsonRejection::JsonDataError(err)) => {
            // Well-formed JSON, wrong shape -> 422
            (StatusCode::UNPROCESSABLE_ENTITY, err.body_text()).into_response()
        }
        Err(JsonRejection::JsonSyntaxError(_)) => {
            // Malformed JSON -> 400
            (StatusCode::BAD_REQUEST, "malformed JSON").into_response()
        }
        Err(JsonRejection::MissingJsonContentType(_)) => {
            // Wrong or missing Content-Type -> 415
            (StatusCode::UNSUPPORTED_MEDIA_TYPE, "expected application/json").into_response()
        }
        Err(_) => {
            // JsonRejection is #[non_exhaustive]; keep a catch-all arm.
            (StatusCode::BAD_REQUEST, "invalid request").into_response()
        }
    }
}

Per extractor - wrap it with WithRejection from axum-extra (feature with-rejection) to convert a rejection into your own error type, which then becomes the response wherever that extractor is used:

use axum::extract::rejection::JsonRejection;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum_extra::extract::WithRejection;

// Your own error type. It must implement IntoResponse, and From<JsonRejection>
// so the framework can convert a Json failure into it.
struct MyRejection;
impl From<JsonRejection> for MyRejection {
    fn from(_err: JsonRejection) -> Self {
        MyRejection
    }
}
impl IntoResponse for MyRejection {
    fn into_response(self) -> Response {
        (StatusCode::BAD_REQUEST, "please send valid JSON").into_response()
    }
}

async fn create_user(
    WithRejection(Json(payload), _): WithRejection<Json<CreateUser>, MyRejection>,
) -> Response {
    (StatusCode::CREATED, format!("Created {}", payload.name)).into_response()
}

The handler declares WithRejection<Json<CreateUser>, MyRejection> instead of plain Json<CreateUser>. When the JSON extractor fails, Axum converts the failure into your MyRejection through the From implementation, and your IntoResponse implementation decides the status and body. Every handler that uses this wrapper gets the same custom error for free.

Either way, the customization lives with the extractor or the handler - never in a layer.

Actix-web's Error Type

Actix-web extractors return a Result<T, actix_web::Error>. An extractor failure is converted into a response through the error's ResponseError implementation - bad JSON, for example, is a 400 Bad Request by default, not a 500. (A 500 only appears if the error type has no more specific mapping.) To return a different status or body, you must either:

  • Implement ResponseError for your own error type,
  • Use helper functions like ErrorBadRequest, or
  • Map the error manually.

Example of mapping:

async fn create_user(payload: Result<web::Json<CreateUser>, actix_web::Error>) -> impl Responder {
    match payload {
        Ok(json) => HttpResponse::Created().finish(),
        Err(e) => {
            // e is an actix_web::Error; we can inspect its cause or just return 400
            HttpResponse::BadRequest().body(e.to_string())
        }
    }
}

This is more manual but also more explicit. Axum's default behavior is more beginner-friendly because you get sensible responses without thinking, while Actix-web pushes you to handle errors yourself.

What This Means for You as a Beginner

Which style should you prefer? Both are valid and type-safe, but Axum's extractor style has a few advantages for newcomers:

  • Less boilerplate: No web:: prefix, no .into_inner(), no route macros for basic cases.
  • Automatic error responses: Axum's rejection system returns a sensible status for extraction failures by default (400 for bad path/query values; 400/415/422 for JSON, depending on what went wrong). Actix-web also converts extractor failures into responses by default (bad JSON is a 400 there too), but customizing the error body usually means implementing ResponseError or mapping the error yourself.
  • Compile-time safety for ordering: Axum enforces that body extractors are last, preventing a whole class of runtime bugs.

Actix-web's style, while more verbose, can be more explicit and may appeal to developers who like to see exactly what framework types they are using. Its web:: module groups all extractors in one place, which can help with discovery.

A common misconception is that Axum's extractors are "magic" or hidden. They're not - they are just ordinary types that implement a trait. Once you understand that, the whole system becomes predictable.

Do not confuse extractor types with response types:

Both frameworks have Json<T> extractors and Json<T> response types. They are different types in the same crate. The extractor is for incoming data (request body), the response type is for outgoing data. In Axum, Json<T> is both, but the context (parameter vs return) tells you which one it is. In Actix-web, web::Json<T> is the extractor, and web::Json<T> is also a response type - again, context matters.

Summary

Axum and Actix-web solve the same problem - turning raw HTTP requests into typed handler parameters - with different ergonomic choices. Axum's style is more inference-driven, with extractors as plain types and automatic rejection handling. Actix-web is more explicit, with web:: prefixes and route macros, but still type-safe.

If you're starting a new project and value minimal ceremony and safe defaults, Axum's extractor style will feel smoother. If you prefer a framework that makes its types and routing structure explicit, Actix-web's style might feel more grounded. Both are excellent; the difference is mostly a matter of taste and the kind of errors you want to see while learning.

A quick way to decide between the two styles: if you want the framework to turn bad input into a sensible response with as little code as possible, Axum's extractors and rejections do that for you. If you would rather see every type spelled out and handle each failure yourself, Actix-web's explicit style fits that habit. Either way, the rule that matters most is the one about the body - read it once, with at most one body extractor, and put that extractor last.