Answer#
actix-web handlers are async functions; route attributes bind them to a method and path.
use actix_web::{get, post, test, web, App, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct NewTodo { title: String }
#[derive(Serialize)]
struct Todo { id: u32, title: String }
#[get("/todos/{id}")]
async fn show(id: web::Path<u32>) -> impl Responder {
web::Json(Todo { id: *id, title: "write docs".into() })
}
#[post("/todos")]
async fn create(new: web::Json<NewTodo>) -> impl Responder {
HttpResponse::Created().json(Todo { id: 1, title: new.into_inner().title })
}
fn config(cfg: &mut web::ServiceConfig) {
cfg.service(show).service(create);
}
#[actix_web::main]
async fn main() {
// Same App as in HttpServer::new(|| App::new().configure(config)), driven without a network port.
let app = test::init_service(App::new().configure(config)).await;
let res = test::call_service(&app, test::TestRequest::get().uri("/todos/5").to_request()).await;
println!("GET /todos/5 -> {}", res.status());
println!("{}", String::from_utf8_lossy(&test::read_body(res).await));
let req = test::TestRequest::post().uri("/todos").set_json(serde_json::json!({"title": "buy milk"})).to_request();
let res = test::call_service(&app, req).await;
println!("POST /todos -> {}", res.status());
println!("{}", String::from_utf8_lossy(&test::read_body(res).await));
let req = test::TestRequest::post().uri("/todos").set_json(serde_json::json!({})).to_request();
let res = test::call_service(&app, req).await;
println!("POST /todos with {{}} -> {}", res.status());
println!("{}", String::from_utf8_lossy(&test::read_body(res).await));
let res = test::call_service(&app, test::TestRequest::get().uri("/nope").to_request()).await;
println!("GET /nope -> {}", res.status());
}GET /todos/5 -> 200 OK
{"id":5,"title":"write docs"}
POST /todos -> 201 Created
{"id":1,"title":"buy milk"}
POST /todos with {} -> 400 Bad Request
Json deserialize error: missing field `title` at line 1 column 2
GET /nope -> 404 Not Foundweb::Path<u32>reads{id}from the path.web::Json<T>reads the body, andweb::Json(value)or.json(value)writes one.HttpResponse::Created()gives status 201.- A body without the
titlefield gave 400 with serde's message; an unknown path gave 404. configis a function overweb::ServiceConfig, soHttpServer::new(|| App::new().configure(config))and the tests share one definition.
actix-web = "4.21.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"Common mistakes#
- Forgetting to register a handler with
.service(...): the attribute alone does not add the route. - Building shared state inside the
HttpServer::newclosure (see the thread on actix-web state).
Related questions#
Which one is HttpServer::new calling, and when?#
It calls your closure once per worker thread, so everything created inside is created once per worker.
Axum or actix-web?#
See the thread that compares them.
Sources#
- actix-web documentation: https://docs.rs/actix-web/4.21.0/actix_web/ (read 2026-12-05)
- actix.rs: https://actix.rs/docs/ (read 2026-12-05)