Skip to main content

Your First Route

Mapping URLs to handlers.

Actix 4.9+ 4 min read

# Defining Your First Route

Routing in Actix Web is the process of mapping incoming HTTP requests to specific async functions (handlers). You can define routes in a few different ways, but the most common are using macros or explicitly calling routing methods.

##Macro-based Routing

Actix Web provides convenient attribute macros like #[get("/")], #[post("/user")], etc. These macros abstract away the manual registration process, making your code clean and readable.

code_blocksrust
use actix_web::{get, HttpResponse, Responder};

#[get("/hello")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello!")
}

To register a macro-based route, you use the .service() method on your App:

code_blocksrust
App::new().service(hello)

##Explicit Routing

Sometimes you might prefer or need explicit routing, especially if you want to apply specific middleware to a route or generate routes dynamically. You use the .route() method for this:

code_blocksrust
use actix_web::{web, App, HttpResponse, Responder};

async fn goodbye() -> impl Responder {
    HttpResponse::Ok().body("Goodbye!")
}

// Inside your HttpServer factory:
App::new().route("/bye", web::get().to(goodbye))

##Path Parameters

Routes aren't just static strings. They can contain dynamic parameters that you can extract. Using curly braces {} in the route path signifies a dynamic segment.

code_blocksrust
#[get("/users/{user_id}")]
async fn get_user(path: actix_web::web::Path<u32>) -> impl Responder {
    let user_id = path.into_inner();
    format!("Fetching user with ID: {}", user_id)
}

This flexibility lets you design RESTful APIs efficiently and elegantly.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, web, App, HttpServer, Responder};
2
3#[get("/api/v1/status")]
4async fn status() -> impl Responder {
5 "Status: All systems operational"
6}
7
8async fn manual_route() -> impl Responder {
9 "This was routed explicitly."
10}
11
12#[actix_web::main]
13async fn main() -> std::io::Result<()> {
14 HttpServer::new(|| {
15 App::new()
16 .service(status)
17 .route("/manual", web::get().to(manual_route))
18 })
19 .bind("127.0.0.1:8080")?
20 .run()
21 .await
22}
Was this page helpful?