Skip to main content

Query Parameters

Parsing the query string

Actix 4.9+ 5 min read

# Query Parameters

The query string is the part of a URL after the ? character. It is commonly used for search terms, pagination, or filtering. Actix Web handles query parameters via the web::Query extractor.

#Using web::Query

To extract query parameters, define a struct that derives Deserialize and represents the expected fields. Then, add web::Query<YourStruct> to your handler's parameters.

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

#[derive(Deserialize)]
struct Filter {
    page: Option<u32>,
    keyword: String,
}

async fn search(query: web::Query<Filter>) -> HttpResponse {
    HttpResponse::Ok().body(format!("Searching for {} on page {:?}", query.keyword, query.page))
}

#Optional Parameters

Always use Option<T> for query parameters that might not be present in the request. If you use a non-optional type and the parameter is missing, Actix Web will 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::{web, App, HttpServer, Responder};
2use serde::Deserialize;
3
4#[derive(Deserialize)]
5struct Pagination {
6 page: u32,
7 limit: u32,
8}
9
10async fn list_items(info: web::Query<Pagination>) -> impl Responder {
11 format!("Page {} with limit {}", info.page, info.limit)
12}
13
14#[actix_web::main]
15async fn main() -> std::io::Result<()> {
16 HttpServer::new(|| {
17 App::new().route("/items", web::get().to(list_items))
18 })
19 .bind(("127.0.0.1", 8080))?
20 .run()
21 .await
22}
Was this page helpful?