# How do I define routes and a JSON API in actix-web?
Source: https://ruststudio.org/community/t/187/how-do-i-define-routes-and-a-json-api-in-actix-web
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | 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
Category: Help and questions | Kind: FAQ | Tags: actix-web, routing, json, web | Views: 0

## 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.

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

```rust title=src/main.rs
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.

```toml title=Cargo.toml
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).

## 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)
