FAQ - Help and questions

How do I define routes and a JSON API in actix-web?

#actix-web#routing#json#webpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Mark handlers with #[get] and #[post], read path values with web::Path and bodies with web::Json, and return web::Json or HttpResponse::Created().json(..). Collect routes in a configure function so the same App can be built by the server and by tests. A body that does not match gives 400.

Checked with rustc 1.93.0, actix-web 4.21.0, serde 1.0.229, serde_json 1.0.154, tokio 1.54.1, Windows 11; driven with actix_web::test

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

actix-web handlers are async functions; route attributes bind them to a method and path.

src/main.rsrust
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());
}
text
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 Found
  • web::Path<u32> reads {id} from the path.
  • web::Json<T> reads the body, and web::Json(value) or .json(value) writes one.
  • HttpResponse::Created() gives status 201.
  • A body without the title field gave 400 with serde's message; an unknown path gave 404.
  • config is a function over web::ServiceConfig, so HttpServer::new(|| App::new().configure(config)) and the tests share one definition.
Cargo.tomltoml
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::new closure (see the thread on actix-web state).

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet