Rocket vs Axum handler signatures

Compare how handler functions are written in Axum and Rocket, focusing on function parameters, extractors, return types, and the underlying design differences.

When you build a web service in Rust, the core piece you write over and over is the handler - the function that receives an HTTP request and produces an HTTP response. Both Axum and Rocket make this easy, but they take very different approaches to how that function is declared and how its arguments are supplied. This page focuses entirely on handler signatures: the shape of the function, how you ask for data from the request, and what you are allowed to return. If you have already seen how Axum is macro-free and Rocket relies on attribute macros, this article will show exactly how that plays out in the function definitions themselves.

We will start with the simplest possible handler, then add path parameters, query strings, request bodies, shared state, and custom return types. Every example is complete enough to run on its own, and we'll point out the differences as they appear.

A minimal handler with no parameters

The simplest handler does not need any data from the request. It just returns a fixed response. In Axum, you write an async function that returns something implementing IntoResponse. In Rocket, you write a regular function (sync or async) and annotate it with a route attribute.

Axum

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

The handler hello takes zero arguments. It returns a string slice, which Axum knows how to turn into an HTTP response with status 200 OK and the text as the body. The async keyword is required because Axum handlers must be asynchronous - they run inside the Tokio runtime and may await other operations.

Rocket

#[macro_use] extern crate rocket;
#[get("/")]
fn hello() -> &'static str {
    "Hello from Rocket"
}
#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![hello])
}

Here the handler is a plain fn, not async. The #[get("/")] attribute tells Rocket that this function handles GET /. It also takes no arguments. Rocket can run the handler synchronously because it is fast enough for trivial cases, but you can also make it async by writing async fn if you need to await something inside.

Async vs sync:

Axum requires all handlers to be async because the framework is built on top of Tokio and expects every handler to participate in the asynchronous runtime. Rocket supports both fn and async fn handlers; choose async only when the body contains .await.

The important early difference: in Axum, the route is connected to the handler outside the function, using Router::route("/", get(hello)). In Rocket, the route is attached inside the function through the #[get("/")] attribute. That affects what the function signature can contain, as we'll see next.

Handlers that read path parameters

Most real handlers need data from the URL path, like /users/42 where 42 is the user ID. Both frameworks let you access that value, but the way you declare it in the handler is completely different.

Axum: type-driven extractors as parameters

In Axum, you add a parameter of type Path<T> to the handler. Path is an extractor - a type that tells Axum to pull the matching segment from the URL and try to convert it into T. The route itself uses {id} to mark the dynamic segment.

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

Notice the parameter pattern Path(user_id): Path<u64>. That's a Rust tuple struct pattern. Path<u64> is the extractor type, and user_id is the local name for the inner u64 value. Axum looks at the route /users/{id} and the extractor Path<u64>, sees that there is one dynamic segment, attempts to parse the string into a u64, and if it succeeds, passes it to the function. If parsing fails, Axum automatically returns a 400 Bad Request response before your handler ever runs.

Rocket: macro‑declared parameters matched by name

Rocket's approach is to declare the dynamic segments directly in the route attribute using <name>. The handler then takes a parameter with exactly the same name, and Rocket passes the parsed value as that argument.

#[macro_use] extern crate rocket;
#[get("/users/<id>")]
fn get_user(id: u64) -> String {
    format!("Looking up user {id}")
}
#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![get_user])
}

The #[get("/users/<id>")] attribute tells Rocket that the path after /users/ is a dynamic segment named id. The function parameter id: u64 has the same name, so Rocket knows to pass the parsed number there. Like Axum, if the value cannot be parsed as a u64, Rocket returns a 404 Not Found (or a configurable error) without calling the handler.

Name matching is critical in Rocket:

In Rocket, the parameter name in the function must match the placeholder name in the route attribute. If you write <user_id> in the attribute but name the argument id, Rocket will fail to compile because it cannot find a matching route parameter. Axum does not have this issue - the extractor type is enough.

To handle multiple path parameters, Axum lets you either use multiple Path extractors or a tuple Path<(T1, T2)>. Rocket lists them in the attribute and as separate arguments.

Axum with multiple path parameters

use axum::extract::Path;
async fn get_comment(
    Path((post_id, comment_id)): Path<(u64, u64)>,
) -> String {
    format!("Post {post_id}, comment {comment_id}")
}
// route: /posts/{post_id}/comments/{comment_id}

Rocket with multiple path parameters

#[get("/posts/<post_id>/comments/<comment_id>")]
fn get_comment(post_id: u64, comment_id: u64) -> String {
    format!("Post {post_id}, comment {comment_id}")
}

Both are readable. The Axum version groups the values into a tuple, which is useful when you want to keep all path values together. Rocket keeps them as separate named arguments.

Handlers that read query string parameters

Query parameters come after the ? in the URL, like /search?q=rust&page=2. Both frameworks can parse them, but again the signature differs.

Axum: use the Query<T> extractor with a struct

In Axum, you define a struct that derives Deserialize from Serde, and then accept Query<MyStruct> as a parameter. Axum automatically parses the query string into that struct.

use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    per_page: Option<u32>,
}
async fn list_items(Query(pagination): Query<Pagination>) -> String {
    let page = pagination.page.unwrap_or(1);
    let per_page = pagination.per_page.unwrap_or(20);
    format!("Page {page}, {per_page} items per page")
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/items", get(list_items));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The Query<Pagination> extractor deserializes the query string into a Pagination struct. Fields that are missing become None because they are Option. You can also use required fields with non-Option types; then Axum returns 400 Bad Request if a required query parameter is absent.

Rocket: query parameters as separate function arguments

Rocket expects you to declare each query parameter in the route attribute using ?<name>&<other>, and then provide matching function parameters.

#[get("/items?<page>&<per_page>")]
fn list_items(page: Option<u32>, per_page: Option<u32>) -> String {
    let page = page.unwrap_or(1);
    let per_page = per_page.unwrap_or(20);
    format!("Page {page}, {per_page} items per page")
}

Here #[get("/items?<page>&<per_page>")] tells Rocket that the path /items may have two query parameters: page and per_page. Both are declared as Option<u32> because they are optional. If you declare page: u32 without Option, then the parameter becomes required; a request without ?page=... will not match the route and will produce a 404.

Struct vs separate parameters:

Axum groups related query parameters into a single deserializable struct, which scales well when you have many optional fields and want to reuse validation logic. Rocket forces you to list every query parameter separately in the attribute and the function signature, which is explicit but can become long.

Handlers that read a JSON request body

When a client sends a POST request with a JSON body, you need to parse that body into a Rust struct. Both frameworks support this, but the body‑handling rules are different.

Axum: Json<T> extractor

In Axum, you accept a Json<T> parameter. Axum reads the entire request body and deserializes it as JSON into T. The route must be set up with post (or put, etc.).

use axum::{routing::post, Json, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
async fn create_user(Json(input): Json<CreateUser>) -> String {
    format!("Created user {} with email {}", input.name, input.email)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", post(create_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The handler takes a single Json<CreateUser> parameter. Axum consumes the request body and rejects bad input with a specific status: 400 Bad Request if the JSON text itself is malformed, 422 Unprocessable Entity if the JSON is well-formed but does not match the struct, and 415 Unsupported Media Type if the request has no JSON Content-Type header. You can combine it with other extractors like Path or Query, but only one body‑consuming extractor is allowed per handler, and it must be the last parameter.

Rocket: data guard and Json<T> argument

Rocket uses a data guard. You declare the parameter in the route attribute with data = "<name>" and then add a function parameter of type Json<T> (or Form<T> for form data). Rocket reads the body and parses it for you.

#[macro_use] extern crate rocket;
use rocket::serde::{json::Json, Deserialize};
#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct CreateUser {
    name: String,
    email: String,
}
#[post("/users", data = "<input>")]
fn create_user(input: Json<CreateUser>) -> String {
    format!("Created user {} with email {}", input.name, input.email)
}
#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![create_user])
}

Here the attribute includes data = "<input>", and the function argument is named input of type Json<CreateUser>. Rocket enforces that the body‑consuming parameter is declared in the attribute and appears in the signature. You cannot accidentally have two body extractors because the attribute would not allow it.

Body extractor ordering:

In Axum, if you use a body‑consuming extractor like Json, it must be the last parameter. Putting it before other extractors will cause a compile error. In Rocket, the data guard is placed wherever the macro expects it - but the convention is to put it last in the function signature as well, because Rocket processes it last during request handling.

Handlers that access shared application state

Almost every real service needs to share some data across handlers: a database connection pool, configuration, or an in‑memory cache. Both frameworks let you inject state into handlers, but the mechanism is different.

Axum: State<T> extractor

In Axum, you attach state to the Router using .with_state(...). Then any handler can accept a State<T> extractor to get a reference to that shared value.

use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    message: String,
}
async fn index(State(state): State<Arc<AppState>>) -> String {
    format!("Server says: {}", state.message)
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        message: "Hello from shared state".to_string(),
    });
    let app = Router::new()
        .route("/", get(index))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

State<Arc<AppState>> is an extractor that pulls the shared state from the request context. Because the state is stored as an Arc, you can clone it cheaply inside handlers. The .with_state(state) call on the router makes the state available to all routes in that router.

Rocket: &State<T> parameter with managed state

Rocket uses a managed state system. You register a value with .manage(...) on the Rocket instance, and then any handler can receive a &State<T> parameter to access it. Rocket checks managed state at runtime, not at compile time (see the note below) - the type T is known to the compiler, but whether a value of that type was actually registered is only verified when the application launches.

#[macro_use] extern crate rocket;
use rocket::State;
struct AppState {
    message: String,
}
#[get("/")]
fn index(state: &State<AppState>) -> String {
    format!("Server says: {}", state.message)
}
#[launch]
fn rocket() -> _ {
    rocket::build()
        .manage(AppState { message: "Hello from shared state".to_string() })
        .mount("/", routes![index])
}

In Rocket, you do not need to wrap the state in Arc because Rocket handles the shared ownership internally. The &State<AppState> parameter tells Rocket to look up an instance of AppState that was previously .manage()d. If the state has not been registered, Rocket does not return a compile error - the code compiles fine. Instead, Rocket detects the missing state at runtime through sentinels: it refuses to launch the application, and in the edge cases where a sentinel cannot see the problem, the offending route is not called and the client gets a 500 Internal Server Error.

Compile-time vs runtime state: the real contrast:

This is the sharpest difference between the two frameworks' state systems. In Axum, the state type is part of the Router<S> type itself: .with_state(state) fixes S, and a handler asking for State<T> where T does not match S fails to compile. In Rocket, .manage() and &State<T> are only connected at runtime, so forgetting .manage() is a launch-time failure (or a 500 in sentinel edge cases), not a compiler error. Axum catches the mistake before the program runs; Rocket catches it when the program starts.

State injection is type-based in both:

Both frameworks use the type of the state to identify what to inject. In Axum, the State<T> extractor is matched to whatever .with_state() was given (which must be the same T). In Rocket, &State<T> is matched to a managed value of type T. This means you cannot accidentally pass the wrong kind of state.

Return types and error handling

A handler must return something that can become an HTTP response. Both frameworks provide a trait for this: Axum uses IntoResponse, Rocket uses Responder. Many common Rust types implement these traits automatically.

Axum return types

Any type that implements IntoResponse works. That includes:

  • String, &str, &'static str
  • Json<T>, Html<T>, Bytes
  • StatusCode
  • Tuples like (StatusCode, Json<T>)
  • Result<T, E> where both T and E implement IntoResponse
  • Custom types that you implement IntoResponse for

Here is an example returning different types:

use axum::{http::StatusCode, response::Html, Json};
use serde_json::json;
async fn plain_text() -> &'static str {
    "Hello"
}
async fn json_response() -> Json<serde_json::Value> {
    Json(json!({ "message": "Hello JSON" }))
}
async fn html_response() -> Html<&'static str> {
    Html("<h1>Hello HTML</h1>")
}
async fn created() -> (StatusCode, Json<serde_json::Value>) {
    (StatusCode::CREATED, Json(json!({ "id": 1 })))
}

Handling errors is typically done by returning a Result. The Err variant can be anything that implements IntoResponse, often a custom error type or a (StatusCode, String).

Rocket return types

Rocket uses the Responder trait, implemented for similar types:

  • String, &str, &'static str
  • Json<T>, Html<T>, Content<T>
  • Status
  • (Status, T) where T: Responder
  • Result<T, E> where both T and E implement Responder
  • Custom types that implement Responder

A small example:

use rocket::http::Status;
use rocket::response::content::Html;
use rocket::serde::json::Json;
#[get("/plain")]
fn plain_text() -> &'static str {
    "Hello"
}
#[get("/json")]
fn json_response() -> Json<serde_json::Value> {
    Json(serde_json::json!({ "message": "Hello JSON" }))
}
#[get("/html")]
fn html_response() -> Html<&'static str> {
    Html("<h1>Hello HTML</h1>")
}
#[post("/create")]
fn created() -> (Status, Json<serde_json::Value>) {
    (Status::Created, Json(serde_json::json!({ "id": 1 })))
}

Notice that Rocket uses its own Json type from rocket::serde::json::Json, while Axum re-exports axum::Json. The overall idea is identical.

Complete side-by-side example

To bring everything together, here is a small API with one route that reads a path parameter, query parameters, and a JSON body, then returns a JSON response. We'll show both frameworks.

Axum version (full main.rs)

use axum::{
    extract::{Path, Query, State},
    routing::post,
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    db_name: String,
}
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
#[derive(Serialize)]
struct UserResponse {
    id: u64,
    name: String,
    email: String,
}
async fn create_user(
    State(state): State<Arc<AppState>>,
    Path(user_id): Path<u64>,
    Query(pagination): Query<Pagination>,
    Json(input): Json<CreateUser>,
) -> Json<UserResponse> {
    let page = pagination.page.unwrap_or(1);
    println!("Using database {}", state.db_name);
    println!("Creating user {} on page {}", input.name, page);
    Json(UserResponse {
        id: user_id,
        name: input.name,
        email: input.email,
    })
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        db_name: "my_db".to_string(),
    });
    let app = Router::new()
        .route("/users/{id}", post(create_user))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Rocket version (full main.rs)

#[macro_use] extern crate rocket;
use rocket::serde::{json::Json, Deserialize, Serialize};
use rocket::State;
struct AppState {
    db_name: String,
}
#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct CreateUser {
    name: String,
    email: String,
}
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
struct UserResponse {
    id: u64,
    name: String,
    email: String,
}
#[post("/users/<id>?<page>", data = "<input>")]
fn create_user(
    id: u64,
    page: Option<u32>,
    input: Json<CreateUser>,
    state: &State<AppState>,
) -> Json<UserResponse> {
    let page = page.unwrap_or(1);
    println!("Using database {}", state.db_name);
    println!("Creating user {} on page {}", input.name, page);
    Json(UserResponse {
        id,
        name: input.name.clone(),
        email: input.email.clone(),
    })
}
#[launch]
fn rocket() -> _ {
    rocket::build()
        .manage(AppState { db_name: "my_db".to_string() })
        .mount("/", routes![create_user])
}

Notice the ordering of parameters in each. In Axum, the body extractor Json must be last, and state can be anywhere (here first). In Rocket, the data guard input is conventionally placed just before state, and the path/query parameters appear first. The exact order in Rocket is flexible as long as the names match, but placing the body last is idiomatic.

At most one body extractor, and it must be last:

Axum strictly enforces that at most one extractor consumes the request body, and it must be the last parameter. If you place Json<T> before State<T>, the code does not compile, because only the last parameter is allowed to consume the body. Rocket does not have this restriction because the macro handles the ordering internally, but it is still good practice to put data guards last.

Common mistakes and how to avoid them

Because the two frameworks have such different models, beginners often carry habits from one to the other and hit predictable errors.

Axum: forgetting the extractor wrapper:

A frequent Axum mistake is writing async fn handler(id: u64) instead of async fn handler(Path(id): Path<u64>). The compiler error will say that u64 does not implement FromRequestParts (or FromRequest). To fix it, wrap the value in the appropriate extractor type.

Rocket: mismatched parameter names:

In Rocket, the placeholder in the route attribute must match the function parameter name exactly. Writing #[get("/users/<user_id>")] but then fn handler(id: u64) will produce a compile error about an unmatched parameter. Always check both the attribute and the signature.

Rocket: missing data guard declaration:

If a Rocket handler takes a Json<T> or Form<T> parameter but the route attribute does not include data = "<name>", Rocket will not treat it as body data and will instead try to find a request guard named after the parameter, leading to confusing errors. Always add data = "<name>" for body parameters.

Both frameworks catch type mismatches at compile time:

Unlike dynamically typed frameworks where a wrong parameter type fails at runtime, both Axum and Rocket verify handler signatures when the program compiles. This means many errors are caught before you ever run the server.

Summary

Handler signatures in Axum and Rocket reflect their core design philosophies. Axum handlers are plain async functions whose parameters are type-driven extractors - the type itself tells the framework what to do, and there is no magic outside the function. Rocket handlers are attached to routes via attribute macros, and their parameters are declared by name in the route attribute; the macro generates the extraction code and wires the arguments for you.

This leads to different trade-offs. Axum's approach is more explicit and composes well with Rust's type system; it also scales naturally when you have many independent extractors. Rocket's approach is more declarative and can be more concise for simple routes, because the route and the parameter list live in one place. The important thing for a beginner is to understand that neither is better in an absolute sense - they simply ask you to think about request data in different ways.

When you move on to building real applications, you'll likely find that Axum's handler signatures feel more like ordinary Rust functions, while Rocket's feel more like a DSL. Both are perfectly valid, and the choice often comes down to which mental model you prefer.