actix-web
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.
Top Related Projects
Ergonomic and modular web framework built with Tokio, Tower, and Hyper
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 Extensible, Concurrent Web Framework for Rust
An HTTP library for Rust
Quick Overview
Actix-web is a powerful, pragmatic, and fast web framework for Rust. It provides a robust foundation for building high-performance web applications and APIs, leveraging Rust's safety and concurrency features while offering an ergonomic and flexible API.
Pros
- Extremely fast performance, consistently ranking among the top web frameworks in benchmarks
- Built on top of the actor framework Actix, providing excellent concurrency and scalability
- Strong type safety and compile-time checks, thanks to Rust's type system
- Flexible and extensible architecture, allowing for easy customization and middleware integration
Cons
- Steeper learning curve compared to some other web frameworks, especially for developers new to Rust
- Smaller ecosystem and fewer third-party libraries compared to more established web frameworks
- Documentation can be challenging for beginners, although it has improved significantly over time
- Frequent API changes in earlier versions (though it has stabilized more recently)
Code Examples
- Basic "Hello, World!" server:
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello, World!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(hello))
.bind("127.0.0.1:8080")?
.run()
.await
}
- JSON handling with derived structs:
use actix_web::{post, web, App, HttpServer, Responder};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Info {
name: String,
age: u32,
}
#[derive(Serialize)]
struct Response {
message: String,
}
#[post("/echo")]
async fn echo(info: web::Json<Info>) -> impl Responder {
let response = Response {
message: format!("{} is {} years old", info.name, info.age),
};
web::Json(response)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(echo))
.bind("127.0.0.1:8080")?
.run()
.await
}
- Middleware example (logging):
use actix_web::{middleware::Logger, App, HttpServer};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
HttpServer::new(|| {
App::new()
.wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i"))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Getting Started
To start using actix-web, add it to your Cargo.toml
:
[dependencies]
actix-web = "4.3"
Then, create a basic server in your main.rs
:
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello, 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
}
Run your application with cargo run
and visit http://localhost:8080
in your browser.
Competitor Comparisons
Ergonomic and modular web framework built with Tokio, Tower, and Hyper
Pros of Axum
- Simpler and more intuitive API design, making it easier for beginners to get started
- Tighter integration with the Tokio ecosystem, potentially leading to better performance
- More flexible routing system with support for nested routers
Cons of Axum
- Smaller community and ecosystem compared to Actix Web
- Less mature and battle-tested in production environments
- Fewer built-in features, requiring more third-party dependencies for advanced functionality
Code Comparison
Axum route definition:
async fn hello_world() -> &'static str {
"Hello, World!"
}
let app = Router::new().route("/", get(hello_world));
Actix Web route definition:
async fn hello_world() -> impl Responder {
HttpResponse::Ok().body("Hello, World!")
}
App::new().service(web::resource("/").route(web::get().to(hello_world)))
Both frameworks offer concise and readable route definitions, but Axum's approach is slightly more straightforward. Actix Web provides more control over the response structure out of the box, while Axum focuses on simplicity.
A super-easy, composable, web server framework for warp speeds.
Pros of Warp
- More lightweight and minimalist design, leading to potentially faster compile times
- Stronger focus on type-safe routing and composability
- Easier to understand and get started with for beginners
Cons of Warp
- Less mature ecosystem and fewer extensions compared to Actix-web
- May not perform as well as Actix-web in high-load scenarios
- Fewer built-in features, requiring more manual implementation or third-party crates
Code Comparison
Warp:
let hello = warp::path!("hello" / String)
.map(|name| format!("Hello, {}!", name));
warp::serve(hello).run(([127, 0, 0, 1], 3030)).await;
Actix-web:
#[get("/hello/{name}")]
async fn hello(web::Path(name): web::Path<String>) -> impl Responder {
format!("Hello, {}!", name)
}
HttpServer::new(|| App::new().service(hello))
.bind("127.0.0.1:3030")?
.run()
.await
Both frameworks offer concise and expressive ways to define routes and handlers. Warp's approach is more functional and composable, while Actix-web uses attribute macros for a more declarative style. Actix-web's code is slightly more verbose but provides more built-in structure.
A web framework for Rust.
Pros of Rocket
- More intuitive and developer-friendly syntax
- Built-in form handling and templating support
- Automatic request parsing and type conversion
Cons of Rocket
- Slightly slower performance compared to Actix-web
- Requires nightly Rust compiler (as of the latest stable release)
- Less flexible for low-level customization
Code Comparison
Rocket example:
#[get("/<name>/<age>")]
fn hello(name: String, age: u8) -> String {
format!("Hello, {} year old named {}!", age, name)
}
Actix-web example:
async fn hello(info: web::Path<(String, u8)>) -> impl Responder {
let (name, age) = info.into_inner();
format!("Hello, {} year old named {}!", age, name)
A flexible web framework that promotes stability, safety, security and speed.
Pros of Gotham
- Emphasizes type-safe routing and middleware
- Designed with a focus on developer ergonomics and ease of use
- Supports asynchronous request handling out of the box
Cons of Gotham
- Smaller community and ecosystem compared to Actix-web
- Less mature and battle-tested in production environments
- Fewer features and integrations available
Code Comparison
Gotham route definition:
fn router() -> Router {
build_simple_router(|route| {
route.get("/").to(say_hello);
})
}
Actix-web route definition:
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(web::resource("/").to(say_hello))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Both frameworks offer concise and readable route definitions, with Gotham focusing on type-safe routing and Actix-web providing a more flexible approach. Actix-web's ecosystem and performance make it a popular choice for production applications, while Gotham's emphasis on developer ergonomics and type safety may appeal to those prioritizing code maintainability and correctness.
An Extensible, Concurrent Web Framework for Rust
Pros of Iron
- Simpler and more lightweight framework, easier to learn for beginners
- More flexible middleware system, allowing for greater customization
- Longer-established project with a stable API
Cons of Iron
- Less active development and community support
- Lower performance compared to modern alternatives
- Fewer built-in features and integrations
Code Comparison
Iron:
fn hello_world(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Hello World!")))
}
Iron::new(hello_world).http("localhost:3000").unwrap();
Actix-web:
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello World!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(hello))
.bind("127.0.0.1:8080")?
.run()
.await
}
Iron provides a more straightforward approach with less boilerplate, while Actix-web offers a more modern, async-first API with additional features and better performance. Actix-web's code is more verbose but provides clearer structure and better support for complex applications.
An HTTP library for Rust
Pros of Hyper
- Lower-level HTTP library, offering more flexibility and control
- Supports both client and server-side HTTP implementations
- Highly performant and lightweight
Cons of Hyper
- Requires more boilerplate code for basic web applications
- Steeper learning curve for beginners
- Less built-in functionality compared to full-featured web frameworks
Code Comparison
Actix-web example:
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello, World!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(hello))
.bind("127.0.0.1:8080")?
.run()
.await
}
Hyper example:
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
async fn hello(_: Request<Body>) -> Result<Response<Body>, hyper::Error> {
Ok(Response::new(Body::from("Hello, World!")))
}
#[tokio::main]
async fn main() {
let make_svc = make_service_fn(|_conn| async {
Ok::<_, hyper::Error>(service_fn(hello))
});
let addr = ([127, 0, 0, 1], 8080).into();
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}
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
Features
- Supports HTTP/1.x and HTTP/2
- Streaming and pipelining
- Powerful request routing with optional macros
- Full Tokio compatibility
- Keep-alive and slow requests handling
- Client/server WebSockets support
- Transparent content compression/decompression (br, gzip, deflate, zstd)
- Multipart streams
- Static assets
- SSL support using OpenSSL or Rustls
- Middlewares (Logger, Session, CORS, etc)
- Integrates with the
awc
HTTP client - Runs on stable Rust 1.72+
Documentation
Example
Dependencies:
[dependencies]
actix-web = "4"
Code:
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
format!("Hello {name}!")
}
#[actix_web::main] // or #[tokio::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(greet)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
More Examples
- Hello World
- Basic Setup
- Application State
- JSON Handling
- Multipart Streams
- MongoDB Integration
- Diesel Integration
- SQLite Integration
- Postgres Integration
- Tera Templates
- Askama Templates
- HTTPS using Rustls
- HTTPS using OpenSSL
- Simple WebSocket
- WebSocket Chat
You may consider checking out this directory for more examples.
Benchmarks
One of the fastest web frameworks available according to the TechEmpower Framework Benchmark.
License
This project is licensed under either of the following licenses, at your option:
- Apache License, Version 2.0, (LICENSE-APACHE or [http://www.apache.org/licenses/LICENSE-2.0])
- MIT license (LICENSE-MIT or [http://opensource.org/licenses/MIT])
Code of Conduct
Contribution to the actix/actix-web
repo is organized under the terms of the Contributor Covenant. The Actix team promises to intervene to uphold that code of conduct.
Top Related Projects
Ergonomic and modular web framework built with Tokio, Tower, and Hyper
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 Extensible, Concurrent Web Framework for Rust
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