pub struct Query<T>(pub T);
query
only.Expand description
Extractor that deserializes query strings into some type.
T
is expected to implement serde::Deserialize
.
§Differences from axum::extract::Query
This extractor uses serde_html_form
under-the-hood which supports multi-value items. These
are sent by multiple <input>
attributes of the same name (e.g. checkboxes) and <select>
s
with the multiple
attribute. Those values can be collected into a Vec
or other sequential
container.
§Example
use axum::{routing::get, Router};
use axum_extra::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: usize,
per_page: usize,
}
// This will parse query strings like `?page=2&per_page=30` into `Pagination`
// structs.
async fn list_things(pagination: Query<Pagination>) {
let pagination: Pagination = pagination.0;
// ...
}
let app = Router::new().route("/list_things", get(list_things));
If the query string cannot be parsed it will reject the request with a 400 Bad Request
response.
For handling values being empty vs missing see the query-params-with-empty-strings example.
While Option<T>
will handle empty parameters (e.g. param=
), beware when using this with a
Vec<T>
. If your list is optional, use Vec<T>
in combination with #[serde(default)]
instead of Option<Vec<T>>
. Option<Vec<T>>
will handle 0, 2, or more arguments, but not one
argument.
§Example
use axum::{routing::get, Router};
use axum_extra::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct Params {
#[serde(default)]
items: Vec<usize>,
}
// This will parse 0 occurrences of `items` as an empty `Vec`.
async fn process_items(Query(params): Query<Params>) {
// ...
}
let app = Router::new().route("/process_items", get(process_items));
Tuple Fields§
§0: T