Actix-web vs Axum Macro Usage
Compare how Actix-web and Axum handle routing and handler definitions with and without macros, and what that means for beginners choosing between the two Rust web frameworks.
When you start building a web server in Rust, you quickly meet the idea of a macro. This page compares how two popular Rust web frameworks, Actix-web and Axum, use macros for routing and request handling. If you are new to Rust, a macro is a piece of code that generates more code for you before the compiler runs. It lets you write something short that expands into a larger, repetitive piece of code.
Actix-web leans heavily on macros for defining routes and handlers. Axum intentionally avoids route macros and instead uses ordinary Rust functions and a fluent builder pattern. Both approaches work, but they feel very different when you read and write the code. This page walks through concrete examples so you can see exactly what each style looks like and understand the trade-offs.
What a Macro Does in Rust
Before comparing the two frameworks, let's make sure the word "macro" is clear. In Rust, a macro is a way to write code that writes other code. When you see something like #[get("/")] or println!, that is a macro invocation. The compiler expands it into a larger block of real Rust code before it tries to compile your program.
Macros are useful because they reduce repetition. Instead of writing the same boilerplate for every route in Actix-web, you can put one small attribute above a function, and the macro fills in all the hidden plumbing. The downside is that the generated code is not visible in your editor. You have to trust that the macro does the right thing, and when something goes wrong, the error messages can be confusing because they point to generated code that you never wrote.
A First Look at Actix-web Route Macros
Actix-web uses attribute macros like #[get("/")], #[post("/users")], and #[put("/users/{id}")] to turn a normal Rust function into an HTTP handler for a specific method and path. Here is the smallest possible Actix-web server:
// main.rs
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello from Actix-web!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
You also need these dependencies in Cargo.toml:
[dependencies]
actix-web = "4"
Look at the line #[get("/")]. That is a macro. It tells Actix-web: "Take the function hello and register it as a handler for HTTP GET requests to the root path /." The function itself is just an async fn that returns a string. There is no mention of HTTP in the function body. The macro does all the wiring for you.
Later, inside App::new(), you call .service(hello). The service method expects something that implements a trait called HttpServiceFactory. The macro has already turned your plain function into a type that implements that trait, so you can pass it directly.
Where Do the Macros Come From?:
Actix-web's route macros are re-exported at the crate root. You can import them individually with use actix_web::get;, as the example above does, or use the fully qualified path #[actix_web::get("/")] with no import at all. Many beginners forget the import and get a confusing "cannot find attribute get" error. The fully qualified form avoids that.
The Same Server in Axum Without Route Macros
Axum takes a different approach. There are no route macros at all. Instead, you build a Router by calling methods like .route() and passing the path, the HTTP method, and the handler function. Here is the Axum equivalent of the previous Actix-web server:
// main.rs
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:8080")
.await
.unwrap();
println!("Listening on http://127.0.0.1:8080");
axum::serve(listener, app).await.unwrap();
}
And the dependencies:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
In Axum, get(hello) is just a normal function call. get is a function from axum::routing that takes your handler and creates a MethodRouter. The route method on Router then associates that method router with the path. There is no macro that rewrites hello. The function stays exactly as you wrote it.
The only macros in this Axum example are #[tokio::main] (from the Tokio runtime, not Axum) and possibly println! (from the standard library). Axum itself does not ask you to use any macro for routing.
Comparing Basic Route Registration
Let's put the two side by side for one simple route that returns a fixed string.
Actix-web:
use actix_web::{get, App, HttpServer, Responder};
#[get("/about")]
async fn about() -> impl Responder {
"About page"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(about))
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum:
use axum::{routing::get, Router};
async fn about() -> &'static str {
"About page"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/about", get(about));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice the difference in how the path is attached. In Actix-web, the path string lives in the macro attribute above the function. In Axum, the path string is passed as the first argument to .route(), right next to the method function. Axum keeps the function definition completely free of routing information. That separation can make handlers easier to reuse because the same function could be mounted at different paths in different routers.
Path Parameters: {id} in both - and Axum's old :id
Both frameworks need a way to capture parts of the URL. Actix-web has always used brace syntax like /{id} inside the macro attribute (and {id:regex} for a regex-constrained segment) - it has never had a :param form. Axum 0.8 also uses brace syntax like /{id} inside the .route() path string. The :id form belongs to Axum before 0.8, not to Actix-web, and in Axum 0.8 it panics at registration (see the note below). So the two frameworks agree on path syntax today; the confusion comes from old Axum tutorials.
Actix-web with a path parameter:
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/users/{user_id}")]
async fn get_user(path: web::Path<u32>) -> impl Responder {
let user_id = path.into_inner();
format!("User ID: {}", user_id)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(get_user))
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum with the same path parameter:
use axum::{extract::Path, routing::get, Router};
async fn get_user(Path(user_id): Path<u32>) -> String {
format!("User ID: {}", user_id)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(get_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler signature is different as well. Actix-web uses the web::Path<T> extractor and you call .into_inner() to get the value. Axum uses Path<T> from axum::extract and destructures it directly in the parameter list. The Axum version feels more concise because the extractor is named the same as the type you want, and destructuring gives you the value immediately.
Path Syntax Changed in Axum 0.8:
If you read older Axum tutorials or code from before version 0.8, you will see :id for path parameters. Axum 0.8 switched to {id} to match the syntax used by Rust's format! macro and OpenAPI specifications. The old :id syntax does not silently fail to match - it panics at registration when the Router is built, so the server crashes at startup instead of serving the route. (The Router::without_v07_checks() escape hatch exists only for APIs that genuinely have literal : segments in a path.) Make sure any example you follow says /{id} and not /:id.
Handling Multiple HTTP Methods on the Same Path
Often you want one path to respond to different HTTP methods, like GET /users for listing and POST /users for creating. Actix-web does this by creating two separate handler functions, each with its own macro attribute, and then registering both with .service().
Actix-web:
use actix_web::{get, post, web, App, HttpServer, Responder};
#[get("/users")]
async fn list_users() -> impl Responder {
"List all users"
}
#[post("/users")]
async fn create_user() -> impl Responder {
"Create a new user"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(list_users)
.service(create_user)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum allows you to chain method handlers on a single .route() call:
use axum::{routing::{get, post}, Router};
async fn list_users() -> &'static str {
"List all users"
}
async fn create_user() -> &'static str {
"Create a new user"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(list_users).post(create_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In Axum, get(list_users).post(create_user) builds a MethodRouter that knows how to handle both GET and POST for the same path. You can keep chaining more methods like .put(...), .delete(...), etc. The Actix-web approach separates the method into the attribute macro, so the registration in App::new() is just a list of services. Both approaches work, but Axum groups all methods for a path in one place, which can make it easier to see all operations for a resource at once.
Nested Routes and Resources
Real applications often have routes like /users/{id}/posts/{post_id}. Actix-web uses #[get("/users/{user_id}/posts/{post_id}")] directly. Axum also supports this full path in a single .route() call, but Axum also offers a nest method to group related routes under a common prefix.
Actix-web nested path in one attribute:
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/users/{user_id}/posts/{post_id}")]
async fn get_post(
path: web::Path<(u32, u32)>
) -> impl Responder {
let (user_id, post_id) = path.into_inner();
format!("User {} Post {}", user_id, post_id)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(get_post))
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum direct path:
use axum::{extract::Path, routing::get, Router};
async fn get_post(
Path((user_id, post_id)): Path<(u32, u32)>
) -> String {
format!("User {} Post {}", user_id, post_id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{user_id}/posts/{post_id}", get(get_post));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
But Axum also lets you break this into a nested router, which can be cleaner when you have many routes under /users:
use axum::{
extract::Path,
routing::get,
Router,
};
async fn get_post(
Path((user_id, post_id)): Path<(u32, u32)>
) -> String {
format!("User {} Post {}", user_id, post_id)
}
#[tokio::main]
async fn main() {
let user_routes = Router::new()
.route("/{user_id}/posts/{post_id}", get(get_post));
let app = Router::new()
.nest("/users", user_routes);
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Actix-web also has a scope mechanism for prefixing routes, but its primary routing definition remains the macro attribute. The point here is that Axum's macro-free approach gives you multiple ways to structure routes: full path in one call, or nested routers. Actix-web's macro-based approach tends to flatten route definitions because the path is always attached to the function, though you can still use web::scope for prefixes.
Handler Signatures: Macro Magic vs Explicit Extractors
In Actix-web, the macro does more than just register the route. It also examines your function's parameters and figures out how to extract data from the request. For example, if you write a function that takes web::Path<u32>, the macro knows it needs to parse a path segment. If you take web::Json<T>, it parses the JSON body. The macro generates the glue code that converts the incoming HTTP request into those arguments.
In Axum, there is no macro generating that glue. Instead, the handler parameters are checked by the compiler at compile time through Rust's trait system. Each parameter must implement the FromRequest trait, and the compiler verifies that when the handler is registered with a route. This is why Axum handlers look like ordinary functions with typed parameters: the types themselves carry the extraction logic.
Actix-web handler with multiple extractors:
use actix_web::{get, post, web, App, HttpServer, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
#[post("/users")]
async fn create_user(
user: web::Json<CreateUser>,
) -> impl Responder {
format!("Created {} ({})", user.name, user.email)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(create_user))
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum equivalent:
use axum::{routing::post, Json, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
async fn create_user(
Json(user): Json<CreateUser>,
) -> String {
format!("Created {} ({})", user.name, user.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:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The function bodies are almost identical. The difference is in how the parameters are declared. Actix-web uses web::Json<CreateUser> and then accesses .name and .email through the wrapper. Axum uses Json<CreateUser> and destructures immediately to get user. Axum's approach removes one level of indirection and makes the handler feel like it is just receiving the data directly.
Axum's Type System Does the Work:
Axum's extractor system is a direct consequence of not using route macros. Because the handler is a plain function, the compiler can check the parameter types. If you try to use an extractor that Axum does not implement for your type, you will get a compile-time error that points directly at your handler signature. Actix-web's macros also produce compile-time checks, but the errors can sometimes be harder to understand because they involve generated code.
Return Types: impl Responder vs IntoResponse
Actix-web handlers must return something that implements the Responder trait. The route macro expects that. Many types implement Responder, including String, &'static str, web::Json<T>, and HttpResponse. You can use impl Responder as a convenient return type.
Axum handlers must return something that implements IntoResponse. That includes String, &'static str, Json<T>, StatusCode, and tuples like (StatusCode, Json<T>). Axum does not require impl IntoResponse; you can return concrete types, but often people do use impl IntoResponse for flexibility.
Actix-web returning JSON:
use actix_web::{post, web, App, HttpServer, Responder};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
#[post("/users")]
async fn create_user() -> impl Responder {
web::Json(User { id: 1, name: "Alice".into() })
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(create_user))
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum returning JSON:
use axum::{routing::post, Json, Router};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
async fn create_user() -> Json<User> {
Json(User { id: 1, name: "Alice".into() })
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Both frameworks use the serde crate for serialization, but the wrapper types differ: web::Json vs axum::Json. The Axum version is a little simpler because Json is the type and you return Json<User> directly. In Actix-web, you often write web::Json(...) as an expression and return impl Responder.
What About the #[actix_web::main] and #[tokio::main] Macros?
You have seen two other attribute macros in the examples: #[actix_web::main] and #[tokio::main]. These are not routing macros, but they are important to understand.
#[actix_web::main] is a macro that sets up the Actix runtime and converts your async fn main into a synchronous entry point that the operating system can call. Under the hood, it initializes the Actix system and runs the future to completion.
#[tokio::main] does the same thing for the Tokio async runtime. Axum is built on top of Tokio, so you must use #[tokio::main]. Actix-web historically had its own runtime but in version 4 it can run on Tokio as well. The macro difference here is not a routing macro; it's just an async runtime entry point. The key point is that Axum requires Tokio, and you see the Tokio macro on the main function. Actix-web provides its own macro but can also work with #[tokio::main] if configured correctly.
This page focuses on macro usage for routing and handlers, but keep in mind that both frameworks still use macros from the broader Rust ecosystem for things like serialization (#[derive(Serialize, Deserialize)]) and async entry points. The difference is that Actix-web adds its own route macros, while Axum does not.
Advantages of Macro-Free Routing in Axum
Axum's decision to avoid route macros has several practical benefits for beginners:
- Less hidden magic. When you read an Axum handler, everything it does is in the function body and the type signatures. There is no attribute above the function that changes what the function means.
- Easier to search and navigate. In Axum, the path strings sit inside
.route("/users", ...)calls next to the handler registration, so a search for"/users"finds the route and its wiring together. In Actix-web, the path lives in the macro attribute above the handler, so a search finds the handler - but the registration happens separately, through.service(...), and a route built withweb::resourcecan split the path across several calls. - Better IDE support. Most Rust IDEs can show you the actual function you wrote without expanding macros. With Axum, the function is exactly what you see. With Actix-web, the macro may expand into a large struct that is not visible, making autocomplete and go-to-definition less intuitive.
- Compile-time errors point to your code. If you make a mistake in an Axum handler signature, the compiler usually points to the exact parameter or return type that is wrong. In Actix-web, errors from the route macro can sometimes point to generated code inside the macro expansion, which is confusing.
- Routes can be composed and reused dynamically. Because Axum routes are just data in a
Router, you can build them in loops, conditionally add routes, or even generate routes from a list at runtime. Actix-web's macros are static; you cannot easily register a route from a list of paths without using a different mechanism.
Advantages of Macro-Based Routing in Actix-web
Actix-web's route macros are not without merit. They have been used in production for years and many developers like them.
- Less boilerplate for simple cases. For a single route, the Actix-web code is shorter. The path is attached to the function, so you see the route definition right above the handler. Axum requires a separate
.route()call. - Clear separation of method. The macro name (
get,post,put, etc.) immediately tells you the HTTP method. In Axum, the method is also visible (get(handler)) but appears inside the.route()call, which might be far from the handler definition. - Macros can perform additional compile-time checks. Actix-web's macros can validate that the path string uses valid syntax for parameters and that the handler's arguments are supported extractors. This validation happens at compile time, before you run the server.
- Tradition and familiarity. Many Rust web frameworks before Axum used attribute macros for routing. Developers coming from those frameworks may find Actix-web's style more familiar.
The trade-off is essentially explicitness vs conciseness. Axum values explicitness and discoverability. Actix-web values a terse, attribute-driven style that keeps route definitions close to the handler functions.
Common Beginner Mistakes When Moving Between the Two
Because the syntax is different, beginners often make specific errors when switching from one framework to the other or when reading mixed examples.
Mixing Path Syntax:
The most frequent error is copying Axum's old :param path syntax into Axum 0.8 code. Actix-web never had a :param form - in Actix-web, write #[get("/users/{id}")]. In Axum 0.8, write .route("/users/{id}", get(...)). Older Axum code used :id, but in Axum 0.8 that form panics at registration when the router is built; it does not fail to compile and it does not silently fail to match. Always use braces {} in Axum 0.8+.
Forgetting the Macro Import in Actix-web:
If you write #[get("/")] without importing the get macro, the compiler will say something like "cannot find attribute get in this scope". The fix is to add use actix_web::get; at the top, or use the fully qualified #[actix_web::get("/")]. This confusion does not exist in Axum because get is just a function, not a macro.
Handler Return Type Mismatch:
Actix-web handlers return impl Responder. Axum handlers return something that implements IntoResponse. If you try to return String from an Actix-web handler, it works because String implements Responder. If you try to return String from an Axum handler, it also works because String implements IntoResponse. However, if you return web::Json from an Axum handler by mistake, it will not compile because web::Json is Actix-web's type, not Axum's. Always use the correct wrapper type for the framework you are in.
Correct Setup Leads to Clear Compilation:
When you have the right imports and path syntax, both frameworks compile cleanly. For Axum, you will see no route macros in your code. For Actix-web, the attribute macros will expand and the server will start. If you see errors about missing traits like Handler or ServiceFactory, check that your imports match the framework you intended to use.
How Macros Affect Learning and Debugging
For a beginner, the learning curve is different. Actix-web's macros can hide some of the underlying mechanics, which is nice at first because you don't need to understand how routing works internally. But when something goes wrong, the error messages can be intimidating because they mention HttpServiceFactory, Handler, and generated code that you never wrote.
Axum's explicit approach forces you to understand a little more about how routes are built from the start. You see the Router being constructed, you see the get function, and you see the handler passed in. That transparency helps you build a mental model of what the framework is doing. When an error occurs, it is more likely to point to a line you wrote yourself.
The key takeaway is that Actix-web uses macros to reduce boilerplate, while Axum uses plain functions and a builder API to increase explicitness. Neither is wrong; they are different design philosophies.
A Realistic Example: A Small REST API
Let's close with a slightly larger example that shows the macro usage difference for a small REST API with two resources: users and posts. This will illustrate how the routing structure differs across the two frameworks.
Actix-web version:
use actix_web::{get, post, web, App, HttpServer, Responder};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
id: u32,
name: String,
}
#[derive(Serialize, Deserialize)]
struct Post {
id: u32,
user_id: u32,
title: String,
}
#[get("/users")]
async fn list_users() -> impl Responder {
// In a real app, you'd fetch from a database.
web::Json(vec![
User { id: 1, name: "Alice".into() },
User { id: 2, name: "Bob".into() },
])
}
#[post("/users")]
async fn create_user(user: web::Json<User>) -> impl Responder {
web::Json(user.into_inner())
}
#[get("/users/{id}/posts")]
async fn list_user_posts(
path: web::Path<u32>
) -> impl Responder {
let user_id = path.into_inner();
web::Json(vec![
Post { id: 1, user_id, title: "First post".into() },
])
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(list_users)
.service(create_user)
.service(list_user_posts)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum version of the same API:
use axum::{
extract::Path,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
id: u32,
name: String,
}
#[derive(Serialize, Deserialize)]
struct Post {
id: u32,
user_id: u32,
title: String,
}
async fn list_users() -> Json<Vec<User>> {
Json(vec![
User { id: 1, name: "Alice".into() },
User { id: 2, name: "Bob".into() },
])
}
async fn create_user(Json(user): Json<User>) -> Json<User> {
Json(user)
}
async fn list_user_posts(
Path(user_id): Path<u32>
) -> Json<Vec<Post>> {
Json(vec![
Post { id: 1, user_id, title: "First post".into() },
])
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(list_users).post(create_user))
.route("/users/{id}/posts", get(list_user_posts));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Look at the differences:
- In Actix-web, all route definitions are spread across the
#[get]and#[post]attributes above the functions. TheApp::new()block just lists services. In Axum, theRouter::new()block shows all routes in one place with paths and methods. - The handler signatures are similar, but Axum uses its own extractor types (
Path,Json) and returnsJson<T>directly, while Actix-web usesweb::Path,web::Json, and returnsimpl Responder. - The number of lines is comparable. Actix-web might be slightly shorter because the routing information is embedded in the attributes, but Axum's routing block is more centralized.
Deciding Which Style You Prefer
Now that you have seen many examples, you can make an informed choice. If you value seeing all routes listed together and like the idea of a transparent, type-driven system, Axum's macro-free approach will feel comfortable. If you like having the route definition right above the handler function and don't mind the magic of attribute macros, Actix-web's style will appeal to you.
Both frameworks are mature and used in production. The macro usage is just one aspect of their design. For now, the most important thing is to try writing a small server in each framework and see which code feels more readable to you.
Summary
This page compared how Actix-web and Axum use macros for routing and handler definitions. Actix-web relies on attribute macros like #[get("/")] and #[post("/users")] that attach HTTP metadata directly to handler functions. Axum avoids route macros entirely and instead uses a Router builder with plain function calls like .route("/", get(handler)).
The practical differences show up in how you write path parameters ({id} in both, but Axum 0.8 changed from :id), how you register multiple methods on one path (chained in Axum, separate services in Actix-web), and how extractors and return types are expressed (web::Path vs Path, web::Json vs Json, impl Responder vs IntoResponse). Axum's macro-free approach makes the routing logic explicit and central, while Actix-web's macros keep route definitions close to the handler functions and reduce some boilerplate.
The single most important insight is that Axum's design philosophy favors transparency and type-driven behavior, while Actix-web uses macros to hide repetitive plumbing. As a beginner, writing the same small API in both frameworks will quickly reveal which style matches your way of thinking. When you are ready to explore how middleware works in each framework, you will see that Axum's layer-based approach complements its macro-free routing, while Actix-web's middleware system is independent of its route macros.