Skip to main content

Path Parameters

Extracting dynamic segments from URLs

Actix 4.9+ 6 min read

# Path Parameters

Often, URLs contain dynamic segments that represent resource identifiers, such as user IDs or product slugs. Actix Web makes it easy to extract these segments using path parameters.

#How It Works

You define a dynamic segment in your route path using curly braces, like /users/{user_id}. Actix Web then extracts this value and provides it to your handler via the web::Path extractor.

#Multiple Parameters

You can extract multiple parameters by specifying them in your path and grouping them in a tuple or struct inside web::Path.

code_blocksrust
use actix_web::{get, web, Result};
use serde::Deserialize;

#[derive(Deserialize)]
struct Info {
    user_id: u32,
    friend: String,
}

#[get("/users/{user_id}/{friend}")]
async fn get_friend(info: web::Path<Info>) -> Result<String> {
    Ok(format!("Welcome {}, friend of {}", info.friend, info.user_id))
}

#Type Safety

Because Actix Web uses Serde for deserialization, path parameters are strictly typed. If a request comes in with a non-integer value for user_id in the example above, Actix Web will automatically return a 400 Bad Request error.

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("/users/{id}")]
4async fn get_user(id: web::Path<u32>) -> impl Responder {
5 format!("User ID: {}", id)
6}
7
8#[actix_web::main]
9async fn main() -> std::io::Result<()> {
10 HttpServer::new(|| {
11 App::new().service(get_user)
12 })
13 .bind(("127.0.0.1", 8080))?
14 .run()
15 .await
16}
Was this page helpful?