Top Related Projects
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.
A super-easy, composable, web server framework for warp speeds.
A web framework for Rust.
A flexible web framework that promotes stability, safety, security and speed.
An HTTP library for Rust
Quick Overview
Axum is a web application framework for Rust that focuses on ergonomics and modularity. It's built on top of Tokio and Hyper, providing a robust foundation for building asynchronous, high-performance web services and APIs.
Pros
- Modular and composable architecture, allowing for flexible application design
- Built on top of Tokio, leveraging its powerful async runtime
- Excellent performance and low overhead
- Strong typing and compile-time checks, reducing runtime errors
Cons
- Steeper learning curve for developers new to Rust or async programming
- Smaller ecosystem compared to more established web frameworks
- Documentation, while improving, can be sparse in some areas
- May be overkill for simple web applications
Code Examples
- Basic "Hello, World!" server:
use axum::{Router, routing::get};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
- Handling JSON payloads:
use axum::{Router, routing::post, Json};
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
email: String,
}
async fn create_user(Json(payload): Json<User>) -> String {
format!("Created user: {} ({})", payload.name, payload.email)
}
let app = Router::new().route("/users", post(create_user));
- Using middleware for authentication:
use axum::{Router, middleware};
use tower_http::auth::RequireAuthorizationLayer;
async fn protected() -> &'static str {
"This is a protected route"
}
let app = Router::new()
.route("/protected", get(protected))
.layer(middleware::from_fn(RequireAuthorizationLayer::bearer("secret-token")));
Getting Started
To get started with Axum, add it to your Cargo.toml
:
[dependencies]
axum = "0.6"
tokio = { version = "1", features = ["full"] }
Then, create a basic server in your main.rs
:
use axum::{Router, routing::get};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, Axum!" }));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
Run your server with cargo run
and visit http://localhost:3000
in your browser.
Competitor Comparisons
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.
Pros of Actix-web
- Mature and battle-tested framework with a longer history
- Generally faster performance in benchmarks
- More comprehensive feature set out-of-the-box
Cons of Actix-web
- Steeper learning curve due to more complex API
- Larger codebase and dependencies
- Less idiomatic Rust in some areas due to its actor-based model
Code Comparison
Actix-web:
use actix_web::{web, App, HttpServer, Responder};
async fn hello() -> impl Responder {
"Hello, World!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().route("/", web::get().to(hello))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Axum:
use axum::{routing::get, Router};
async fn hello() -> &'static str {
"Hello, World!"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(hello));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
Both frameworks offer similar functionality, but Axum's API is generally considered more straightforward and idiomatic Rust. Actix-web provides more features and flexibility out-of-the-box, while Axum focuses on simplicity and composability, leveraging the Tokio ecosystem.
A super-easy, composable, web server framework for warp speeds.
Pros of Warp
- More mature and battle-tested, with a longer history of production use
- Offers a more flexible and composable API design
- Provides built-in WebSocket support out of the box
Cons of Warp
- Steeper learning curve due to its more complex API
- Less active development and slower release cycle
- Smaller ecosystem of extensions and middleware
Code Comparison
Warp example:
let hello = warp::path!("hello" / String)
.map(|name| format!("Hello, {}!", name));
warp::serve(hello).run(([127, 0, 0, 1], 3030)).await;
Axum example:
async fn hello(Path(name): Path<String>) -> String {
format!("Hello, {}!", name)
}
let app = Router::new().route("/hello/:name", get(hello));
axum::Server::bind(&"127.0.0.1:3030".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
Both frameworks offer similar functionality, but Axum's routing syntax is more straightforward and closely resembles traditional web frameworks. Warp's approach is more functional and composable, which can be powerful but may require more time to master.
A web framework for Rust.
Pros of Rocket
- Simpler syntax and easier to get started for beginners
- Built-in templating engine (Tera) for server-side rendering
- More opinionated, providing a consistent structure for applications
Cons of Rocket
- Less flexible and customizable compared to Axum
- Slower compile times due to heavy use of macros
- Limited async support (though improving in newer versions)
Code Comparison
Rocket:
#[get("/hello/<name>")]
fn hello(name: &str) -> String {
format!("Hello, {}!", name)
}
Axum:
async fn hello(Path(name): Path<String>) -> String {
format!("Hello, {}!", name)
}
let app = Router::new().route("/hello/:name", get(hello));
Both Rocket and Axum are popular Rust web frameworks, but they have different design philosophies. Rocket aims for simplicity and ease of use, making it a good choice for smaller projects or developers new to Rust. Axum, built on top of Tokio, offers more flexibility and better performance for larger, more complex applications. Rocket's syntax is more declarative, using macros extensively, while Axum takes a more functional approach. The choice between them often depends on the specific needs of the project and the developer's preferences.
A flexible web framework that promotes stability, safety, security and speed.
Pros of Gotham
- More mature project with longer development history
- Extensive middleware ecosystem
- Built-in support for WebSockets
Cons of Gotham
- Less active development and community support
- Steeper learning curve for beginners
- Fewer integrations with modern Rust async ecosystem
Code Comparison
Gotham route definition:
fn router() -> Router {
build_simple_router(|route| {
route.get("/").to(say_hello);
})
}
Axum route definition:
let app = Router::new()
.route("/", get(say_hello));
Both Gotham and Axum are web frameworks for Rust, built on top of the Tokio runtime. Gotham has been around longer and offers a more extensive middleware ecosystem, including built-in WebSocket support. However, Axum has gained popularity due to its simpler API, better integration with modern Rust async patterns, and more active development.
Axum's routing syntax is generally more concise and intuitive, especially for developers familiar with other modern web frameworks. Gotham's routing can be more verbose but offers fine-grained control over request handling.
While Gotham has a longer history, Axum's rapid development and growing community support make it an increasingly attractive choice for new Rust web projects. The choice between the two often depends on specific project requirements and developer preferences.
An HTTP library for Rust
Pros of Hyper
- Lower-level HTTP library, offering more fine-grained control
- Highly performant and battle-tested in production environments
- Supports both client and server-side HTTP implementations
Cons of Hyper
- Steeper learning curve due to its lower-level nature
- Requires more boilerplate code for common web application tasks
- Less opinionated, which can lead to more decision-making for developers
Code Comparison
Axum example:
async fn handler() -> &'static str {
"Hello, World!"
}
let app = Router::new().route("/", get(handler));
Hyper example:
async fn hello_world(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("Hello, World!")))
}
let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(hello_world))
});
Summary
Hyper is a lower-level HTTP library offering more control and flexibility, while Axum is a higher-level web framework built on top of Hyper, providing a more ergonomic API for building web applications. Axum simplifies common tasks and reduces boilerplate, making it easier for developers to create web services quickly. However, Hyper's lower-level approach allows for more fine-tuned optimizations and supports both client and server-side implementations.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
axum
axum
is a web application framework that focuses on ergonomics and modularity.
More information about this crate can be found in the crate documentation.
High level features
- Route requests to handlers with a macro free API.
- Declaratively parse requests using extractors.
- Simple and predictable error handling model.
- Generate responses with minimal boilerplate.
- Take full advantage of the
tower
andtower-http
ecosystem of middleware, services, and utilities.
In particular the last point is what sets axum
apart from other frameworks.
axum
doesn't have its own middleware system but instead uses
tower::Service
. This means axum
gets timeouts, tracing, compression,
authorization, and more, for free. It also enables you to share middleware with
applications written using hyper
or tonic
.
â Breaking changes â
We are currently working towards axum 0.8 so the main
branch contains breaking
changes. See the 0.7.x
branch for what's released to crates.io.
Usage example
use axum::{
routing::{get, post},
http::StatusCode,
Json, Router,
};
use serde::{Deserialize, Serialize};
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
// build our application with a route
let app = Router::new()
// `GET /` goes to `root`
.route("/", get(root))
// `POST /users` goes to `create_user`
.route("/users", post(create_user));
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
// basic handler that responds with a static string
async fn root() -> &'static str {
"Hello, World!"
}
async fn create_user(
// this argument tells axum to parse the request body
// as JSON into a `CreateUser` type
Json(payload): Json<CreateUser>,
) -> (StatusCode, Json<User>) {
// insert your application logic here
let user = User {
id: 1337,
username: payload.username,
};
// this will be converted into a JSON response
// with a status code of `201 Created`
(StatusCode::CREATED, Json(user))
}
// the input to our `create_user` handler
#[derive(Deserialize)]
struct CreateUser {
username: String,
}
// the output to our `create_user` handler
#[derive(Serialize)]
struct User {
id: u64,
username: String,
}
You can find this example as well as other example projects in the example directory.
See the crate documentation for way more examples.
Performance
axum
is a relatively thin layer on top of hyper
and adds very little
overhead. So axum
's performance is comparable to hyper
. You can find
benchmarks here and
here.
Safety
This crate uses #![forbid(unsafe_code)]
to ensure everything is implemented in
100% safe Rust.
Minimum supported Rust version
axum's MSRV is 1.75.
Examples
The examples folder contains various examples of how to use axum
. The
docs also provide lots of code snippets and examples. For full-fledged examples, check out community-maintained showcases or tutorials.
Getting Help
In the axum
's repo we also have a number of examples showing how
to put everything together. Community-maintained showcases and tutorials also demonstrate how to use axum
for real-world applications. You're also welcome to ask in the Discord channel or open a discussion with your question.
Community projects
See here for a list of community maintained crates and projects
built with axum
.
Contributing
ð Thanks for your help improving the project! We are so happy to have
you! We have a contributing guide to help you get involved in the
axum
project.
License
This project is licensed under the MIT license.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in axum
by you, shall be licensed as MIT, without any
additional terms or conditions.
Top Related Projects
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.
A super-easy, composable, web server framework for warp speeds.
A web framework for Rust.
A flexible web framework that promotes stability, safety, security and speed.
An HTTP library for Rust
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot