Skip to main content

axum/
form.rs

1use crate::extract::Request;
2use crate::extract::{rejection::*, FromRequest, RawForm};
3use axum_core::response::{IntoResponse, IntoResponseFailed, Response};
4use axum_core::RequestExt;
5use http::header::CONTENT_TYPE;
6use http::StatusCode;
7use serde_core::{de::DeserializeOwned, Serialize};
8
9/// URL encoded extractor and response.
10///
11/// # As extractor
12///
13/// If used as an extractor, `Form` will deserialize form data from the request,
14/// specifically:
15///
16/// - If the request has a method of `GET` or `HEAD`, the form data will be read
17///   from the query string (same as with [`Query`])
18/// - If the request has a different method, the form will be read from the body
19///   of the request. It must have a `content-type` of
20///   `application/x-www-form-urlencoded` for this to work. If you want to parse
21///   `multipart/form-data` request bodies, use [`Multipart`] instead.
22///
23/// This matches how HTML forms are sent by browsers by default.
24/// In both cases, the inner type `T` must implement [`serde::Deserialize`].
25///
26/// ⚠️ Since parsing form data might require consuming the request body, the `Form` extractor must be
27/// *last* if there are multiple extractors in a handler. See ["the order of
28/// extractors"][order-of-extractors]
29///
30/// [order-of-extractors]: crate::extract#the-order-of-extractors
31///
32/// ```rust
33/// use axum::Form;
34/// use serde::Deserialize;
35///
36/// #[derive(Deserialize)]
37/// struct SignUp {
38///     username: String,
39///     password: String,
40/// }
41///
42/// async fn accept_form(Form(sign_up): Form<SignUp>) {
43///     // ...
44/// }
45/// ```
46///
47/// # As response
48///
49/// `Form` can also be used to encode any type that implements
50/// [`serde::Serialize`] as `application/x-www-form-urlencoded`
51///
52/// ```rust
53/// use axum::Form;
54/// use serde::Serialize;
55///
56/// #[derive(Serialize)]
57/// struct Payload {
58///     value: String,
59/// }
60///
61/// async fn handler() -> Form<Payload> {
62///     Form(Payload { value: "foo".to_owned() })
63/// }
64/// ```
65///
66/// [`Query`]: crate::extract::Query
67/// [`Multipart`]: crate::extract::Multipart
68#[cfg_attr(docsrs, doc(cfg(feature = "form")))]
69#[derive(Debug, Clone, Copy, Default)]
70#[must_use]
71pub struct Form<T>(pub T);
72
73impl<T, S> FromRequest<S> for Form<T>
74where
75    T: DeserializeOwned,
76    S: Send + Sync,
77{
78    type Rejection = FormRejection;
79
80    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
81        let is_get_or_head =
82            req.method() == http::Method::GET || req.method() == http::Method::HEAD;
83
84        match req.extract().await {
85            Ok(RawForm(bytes)) => {
86                let deserializer =
87                    || serde_html_form::Deserializer::new(form_urlencoded::parse(&bytes));
88                let value = crate::util::deserialize_with_error_path(deserializer).map_err(
89                    |err| -> FormRejection {
90                        if is_get_or_head {
91                            FailedToDeserializeForm::from_err(err).into()
92                        } else {
93                            FailedToDeserializeFormBody::from_err(err).into()
94                        }
95                    },
96                )?;
97                Ok(Self(value))
98            }
99            Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)),
100            Err(RawFormRejection::InvalidFormContentType(r)) => {
101                Err(FormRejection::InvalidFormContentType(r))
102            }
103        }
104    }
105}
106
107impl<T> IntoResponse for Form<T>
108where
109    T: Serialize,
110{
111    fn into_response(self) -> Response {
112        // Extracted into separate fn so it's only compiled once for all T.
113        fn make_response(ser_result: Result<String, serde_html_form::ser::Error>) -> Response {
114            match ser_result {
115                Ok(body) => (
116                    [(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())],
117                    body,
118                )
119                    .into_response(),
120                Err(err) => (
121                    StatusCode::INTERNAL_SERVER_ERROR,
122                    IntoResponseFailed,
123                    err.to_string(),
124                )
125                    .into_response(),
126            }
127        }
128
129        make_response(serde_html_form::to_string(&self.0))
130    }
131}
132axum_core::__impl_deref!(Form);
133
134#[cfg(test)]
135mod tests {
136    use crate::{
137        routing::{on, MethodFilter},
138        test_helpers::TestClient,
139        Router,
140    };
141
142    use super::*;
143    use axum_core::body::Body;
144    use http::{Method, Request};
145    use mime::APPLICATION_WWW_FORM_URLENCODED;
146    use serde::{Deserialize, Serialize};
147    use std::fmt::Debug;
148
149    #[derive(Debug, PartialEq, Serialize, Deserialize)]
150    struct Pagination {
151        size: Option<u64>,
152        page: Option<u64>,
153    }
154
155    async fn check_query<T: DeserializeOwned + PartialEq + Debug>(uri: impl AsRef<str>, value: T) {
156        let req = Request::builder()
157            .uri(uri.as_ref())
158            .body(Body::empty())
159            .unwrap();
160        assert_eq!(Form::<T>::from_request(req, &()).await.unwrap().0, value);
161    }
162
163    async fn check_body<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
164        let req = Request::builder()
165            .uri("http://example.com/test")
166            .method(Method::POST)
167            .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())
168            .body(Body::from(serde_html_form::to_string(&value).unwrap()))
169            .unwrap();
170        assert_eq!(Form::<T>::from_request(req, &()).await.unwrap().0, value);
171    }
172
173    #[crate::test]
174    async fn test_form_query() {
175        check_query(
176            "http://example.com/test",
177            Pagination {
178                size: None,
179                page: None,
180            },
181        )
182        .await;
183
184        check_query(
185            "http://example.com/test?size=10",
186            Pagination {
187                size: Some(10),
188                page: None,
189            },
190        )
191        .await;
192
193        check_query(
194            "http://example.com/test?size=10&page=20",
195            Pagination {
196                size: Some(10),
197                page: Some(20),
198            },
199        )
200        .await;
201    }
202
203    #[crate::test]
204    async fn test_form_body() {
205        check_body(Pagination {
206            size: None,
207            page: None,
208        })
209        .await;
210
211        check_body(Pagination {
212            size: Some(10),
213            page: None,
214        })
215        .await;
216
217        check_body(Pagination {
218            size: Some(10),
219            page: Some(20),
220        })
221        .await;
222    }
223
224    #[crate::test]
225    async fn test_incorrect_content_type() {
226        let req = Request::builder()
227            .uri("http://example.com/test")
228            .method(Method::POST)
229            .header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())
230            .body(Body::from(
231                serde_html_form::to_string(&Pagination {
232                    size: Some(10),
233                    page: None,
234                })
235                .unwrap(),
236            ))
237            .unwrap();
238        assert!(matches!(
239            Form::<Pagination>::from_request(req, &())
240                .await
241                .unwrap_err(),
242            FormRejection::InvalidFormContentType(InvalidFormContentType)
243        ));
244    }
245
246    #[tokio::test]
247    async fn deserialize_error_status_codes() {
248        #[allow(dead_code)]
249        #[derive(Deserialize)]
250        struct Payload {
251            a: i32,
252        }
253
254        let app = Router::new().route(
255            "/",
256            on(
257                MethodFilter::GET.or(MethodFilter::POST),
258                |_: Form<Payload>| async {},
259            ),
260        );
261
262        let client = TestClient::new(app);
263
264        let res = client.get("/?a=false").await;
265        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
266        assert_eq!(
267            res.text().await,
268            "Failed to deserialize form: a: invalid digit found in string"
269        );
270
271        let res = client
272            .post("/")
273            .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())
274            .body("a=false")
275            .await;
276        assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
277        assert_eq!(
278            res.text().await,
279            "Failed to deserialize form body: a: invalid digit found in string"
280        );
281    }
282}