Skip to main content

Path

Extracting URL path parameters

Actix 4.9+ 5 min read

# Path Extractor

The web::Path extractor provides a type-safe way to access parameters defined in your route's path. We touched on this in routing, but let's dive deeper into extraction.

#Single Parameters

If you only need a single parameter, you can extract it as a single type.

code_blocksrust
use actix_web::{get, web};

#[get("/user/{id}")]
async fn get_user(id: web::Path<i32>) -> String {
    format!("User ID: {}", id)
}

#Complex Parameters

For multiple parameters, it is best practice to define a struct. Actix Web extracts the variables in the order they appear if using a tuple, or by name if using a struct.

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

#[derive(Deserialize)]
struct Location {
    country: String,
    city: String,
}

#[get("/weather/{country}/{city}")]
async fn weather(loc: web::Path<Location>) -> String {
    format!("Weather for {}, {}", loc.city, loc.country)
}

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};
2use serde::Deserialize;
3
4#[derive(Deserialize)]
5struct PostPath {
6 year: u16,
7 slug: String,
8}
9
10#[get("/posts/{year}/{slug}")]
11async fn get_post(path: web::Path<PostPath>) -> impl Responder {
12 format!("Post: {} from year {}", path.slug, path.year)
13}
14
15#[actix_web::main]
16async fn main() -> std::io::Result<()> {
17 HttpServer::new(|| App::new().service(get_post))
18 .bind(("127.0.0.1", 8080))?
19 .run()
20 .await
21}
Was this page helpful?