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
Implementations§
Source§impl<T> Query<T>where
T: DeserializeOwned,
impl<T> Query<T>where
T: DeserializeOwned,
Sourcepub fn try_from_uri(value: &Uri) -> Result<Self, QueryRejection>
pub fn try_from_uri(value: &Uri) -> Result<Self, QueryRejection>
Attempts to construct a Query
from a reference to a Uri
.
§Example
use axum_extra::extract::Query;
use http::Uri;
use serde::Deserialize;
#[derive(Deserialize)]
struct ExampleParams {
foo: String,
bar: u32,
}
let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap();
let result: Query<ExampleParams> = Query::try_from_uri(&uri).unwrap();
assert_eq!(result.foo, String::from("hello"));
assert_eq!(result.bar, 42);