Actix Web: Routes, Extractors & Shared State
Actix Web is a fast, popular web framework for building HTTP APIs in Rust, frequently near the top of cross-language performance benchmarks -- a combination of Rust's compile-time optimizations, async I/O, and a lean implementation.
Defining Routes
#[get("/users/{id}")]
async fn get_user(path: web::Path<u32>, pool: web::Data<PgPool>) -> impl Responder {
let id = path.into_inner();
let user = fetch_user(&pool, id).await;
HttpResponse::Ok().json(user)
}Extractors
#[post("/users")]
async fn create_user(body: web::Json<CreateUserInput>) -> impl Responder {
// body is already parsed and typed -- Actix returns an
// error response automatically if JSON parsing fails
HttpResponse::Created().json(body.into_inner())
}Shared Application State
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.service(get_user)
.service(create_user)
})
.bind("127.0.0.1:8080")?
.run()
.awaitWhy Async Matters Here
A handler awaiting I/O (a database query) yields control rather than blocking a whole OS thread, letting Actix Web handle many concurrent connections with a relatively small thread pool -- a key factor in its throughput.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free