Skip to main content

Query

Extracting query parameters

Actix 4.9+ 5 min read

# Query Extractor

The web::Query extractor is used to process the URL query string. Actix Web integrates seamlessly with Serde to deserialize query parameters into typed structs.

#Handling Defaults and Options

Because web requests are unpredictable, missing query parameters can cause extraction to fail. To handle this gracefully, use Option<T> or implement Serde default values.

code_blocksrust
use serde::Deserialize;

#[derive(Deserialize)]
struct Pagination {
    #[serde(default = "default_page")]
    page: u32,
    limit: Option<u32>,
}

fn default_page() -> u32 { 1 }

If page is omitted from the URL, it will default to 1. If limit is omitted, it will be None.

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 Search {
6 term: String,
7}
8
9async fn search(q: web::Query<Search>) -> impl Responder {
10 format!("Search results for: {}", q.term)
11}
12
13#[actix_web::main]
14async fn main() -> std::io::Result<()> {
15 HttpServer::new(|| {
16 App::new().route("/search", web::get().to(search))
17 })
18 .bind(("127.0.0.1", 8080))?
19 .run()
20 .await
21}
Was this page helpful?