Skip to main content

axum/extract/
query.rs

1use super::{rejection::*, FromRequestParts};
2use http::{request::Parts, Uri};
3use serde_core::de::DeserializeOwned;
4
5/// Extractor that deserializes query strings into some type.
6///
7/// `T` is expected to implement [`serde::Deserialize`].
8///
9/// # Examples
10///
11/// ```rust,no_run
12/// use axum::{
13///     extract::Query,
14///     routing::get,
15///     Router,
16/// };
17/// use serde::Deserialize;
18///
19/// #[derive(Deserialize)]
20/// struct Pagination {
21///     page: usize,
22///     per_page: usize,
23/// }
24///
25/// // This will parse query strings like `?page=2&per_page=30` into `Pagination`
26/// // structs.
27/// async fn list_things(pagination: Query<Pagination>) {
28///     let pagination: Pagination = pagination.0;
29///
30///     // ...
31/// }
32///
33/// let app = Router::new().route("/list_things", get(list_things));
34/// # let _: Router = app;
35/// ```
36///
37/// If the query string cannot be parsed it will reject the request with a `400
38/// Bad Request` response.
39#[cfg_attr(docsrs, doc(cfg(feature = "query")))]
40#[derive(Debug, Clone, Copy, Default)]
41pub struct Query<T>(pub T);
42
43impl<T, S> FromRequestParts<S> for Query<T>
44where
45    T: DeserializeOwned,
46    S: Send + Sync,
47{
48    type Rejection = QueryRejection;
49
50    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
51        Self::try_from_uri(&parts.uri)
52    }
53}
54
55impl<T> Query<T>
56where
57    T: DeserializeOwned,
58{
59    /// Attempts to construct a [`Query`] from a reference to a [`Uri`].
60    ///
61    /// # Example
62    /// ```
63    /// use axum::extract::Query;
64    /// use http::Uri;
65    /// use serde::Deserialize;
66    ///
67    /// #[derive(Deserialize)]
68    /// struct ExampleParams {
69    ///     foo: String,
70    ///     bar: u32,
71    /// }
72    ///
73    /// let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap();
74    /// let result: Query<ExampleParams> = Query::try_from_uri(&uri).unwrap();
75    /// assert_eq!(result.foo, String::from("hello"));
76    /// assert_eq!(result.bar, 42);
77    /// ```
78    pub fn try_from_uri(value: &Uri) -> Result<Self, QueryRejection> {
79        let query = value.query().unwrap_or_default();
80        let deserializer =
81            || serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes()));
82        let params = crate::util::deserialize_with_error_path(deserializer)
83            .map_err(FailedToDeserializeQueryString::from_err)?;
84        Ok(Self(params))
85    }
86}
87
88axum_core::__impl_deref!(Query);
89
90#[cfg(test)]
91mod tests {
92    use crate::{routing::get, test_helpers::TestClient, Router};
93
94    use super::*;
95    use axum_core::{body::Body, extract::FromRequest};
96    use http::{Request, StatusCode};
97    use serde::Deserialize;
98    use std::fmt::Debug;
99
100    async fn check<T>(uri: impl AsRef<str>, value: T)
101    where
102        T: DeserializeOwned + PartialEq + Debug,
103    {
104        let req = Request::builder()
105            .uri(uri.as_ref())
106            .body(Body::empty())
107            .unwrap();
108        assert_eq!(Query::<T>::from_request(req, &()).await.unwrap().0, value);
109    }
110
111    #[crate::test]
112    async fn test_query() {
113        #[derive(Debug, PartialEq, Deserialize)]
114        struct Pagination {
115            size: Option<u64>,
116            page: Option<u64>,
117        }
118
119        check(
120            "http://example.com/test",
121            Pagination {
122                size: None,
123                page: None,
124            },
125        )
126        .await;
127
128        check(
129            "http://example.com/test?size=10",
130            Pagination {
131                size: Some(10),
132                page: None,
133            },
134        )
135        .await;
136
137        check(
138            "http://example.com/test?size=10&page=20",
139            Pagination {
140                size: Some(10),
141                page: Some(20),
142            },
143        )
144        .await;
145    }
146
147    #[crate::test]
148    async fn correct_rejection_status_code() {
149        #[derive(Deserialize)]
150        #[allow(dead_code)]
151        struct Params {
152            n: i32,
153        }
154
155        async fn handler(_: Query<Params>) {}
156
157        let app = Router::new().route("/", get(handler));
158        let client = TestClient::new(app);
159
160        let res = client.get("/?n=hi").await;
161        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
162        assert_eq!(
163            res.text().await,
164            "Failed to deserialize query string: n: invalid digit found in string"
165        );
166    }
167
168    #[test]
169    fn test_try_from_uri() {
170        #[derive(Deserialize)]
171        struct TestQueryParams {
172            foo: String,
173            bar: u32,
174        }
175        let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap();
176        let result: Query<TestQueryParams> = Query::try_from_uri(&uri).unwrap();
177        assert_eq!(result.foo, String::from("hello"));
178        assert_eq!(result.bar, 42);
179    }
180
181    #[test]
182    fn test_try_from_uri_with_invalid_query() {
183        #[derive(Deserialize)]
184        struct TestQueryParams {
185            _foo: String,
186            _bar: u32,
187        }
188        let uri: Uri = "http://example.com/path?foo=hello&bar=invalid"
189            .parse()
190            .unwrap();
191        let result: Result<Query<TestQueryParams>, _> = Query::try_from_uri(&uri);
192
193        assert!(result.is_err());
194    }
195}