Skip to main content

axum/extract/path/
mod.rs

1//! Extractor that will get captures from the URL and parse them using
2//! [`serde`].
3
4mod de;
5
6pub(crate) mod inner_path;
7
8use crate::{
9    extract::{rejection::*, FromRequestParts},
10    routing::url_params::UrlParams,
11    util::PercentDecodedStr,
12};
13use axum_core::{
14    extract::OptionalFromRequestParts,
15    response::{IntoResponse, Response},
16    RequestPartsExt as _,
17};
18use http::{request::Parts, Extensions, StatusCode};
19use serde_core::de::DeserializeOwned;
20use std::{fmt, sync::Arc};
21
22/// Extractor that will get captures from the URL and parse them using
23/// [`serde`].
24///
25/// Any percent encoded parameters will be automatically decoded. The decoded
26/// parameters must be valid UTF-8, otherwise `Path` will fail and return a `400
27/// Bad Request` response.
28///
29/// # `Option<Path<T>>` behavior
30///
31/// You can use `Option<Path<T>>` as an extractor to allow the same handler to
32/// be used in a route with parameters that deserialize to `T`, and another
33/// route with no parameters at all.
34///
35/// # Example
36///
37/// These examples assume the `serde` feature of the [`uuid`] crate is enabled.
38///
39/// One `Path` can extract multiple captures. It is not necessary (and does
40/// not work) to give a handler more than one `Path` argument.
41///
42/// [`uuid`]: https://crates.io/crates/uuid
43///
44/// ```rust,no_run
45/// use axum::{
46///     extract::Path,
47///     routing::get,
48///     Router,
49/// };
50/// use uuid::Uuid;
51///
52/// async fn users_teams_show(
53///     Path((user_id, team_id)): Path<(Uuid, Uuid)>,
54/// ) {
55///     // ...
56/// }
57///
58/// let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show));
59/// # let _: Router = app;
60/// ```
61///
62/// If the path contains only one parameter, then you can omit the tuple.
63///
64/// ```rust,no_run
65/// use axum::{
66///     extract::Path,
67///     routing::get,
68///     Router,
69/// };
70/// use uuid::Uuid;
71///
72/// async fn user_info(Path(user_id): Path<Uuid>) {
73///     // ...
74/// }
75///
76/// let app = Router::new().route("/users/{user_id}", get(user_info));
77/// # let _: Router = app;
78/// ```
79///
80/// Path segments also can be deserialized into any type that implements
81/// [`serde::Deserialize`]. This includes tuples and structs:
82///
83/// ```rust,no_run
84/// use axum::{
85///     extract::Path,
86///     routing::get,
87///     Router,
88/// };
89/// use serde::Deserialize;
90/// use uuid::Uuid;
91///
92/// // Path segment labels will be matched with struct field names
93/// #[derive(Deserialize)]
94/// struct Params {
95///     user_id: Uuid,
96///     team_id: Uuid,
97/// }
98///
99/// async fn users_teams_show(
100///     Path(Params { user_id, team_id }): Path<Params>,
101/// ) {
102///     // ...
103/// }
104///
105/// // When using tuples the path segments will be matched by their position in the route
106/// async fn users_teams_create(
107///     Path((user_id, team_id)): Path<(String, String)>,
108/// ) {
109///     // ...
110/// }
111///
112/// let app = Router::new().route(
113///     "/users/{user_id}/team/{team_id}",
114///     get(users_teams_show).post(users_teams_create),
115/// );
116/// # let _: Router = app;
117/// ```
118///
119/// If you wish to capture all path parameters you can use `HashMap` or `Vec`:
120///
121/// ```rust,no_run
122/// use axum::{
123///     extract::Path,
124///     routing::get,
125///     Router,
126/// };
127/// use std::collections::HashMap;
128///
129/// async fn params_map(
130///     Path(params): Path<HashMap<String, String>>,
131/// ) {
132///     // ...
133/// }
134///
135/// async fn params_vec(
136///     Path(params): Path<Vec<(String, String)>>,
137/// ) {
138///     // ...
139/// }
140///
141/// let app = Router::new()
142///     .route("/users/{user_id}/team/{team_id}", get(params_map).post(params_vec));
143/// # let _: Router = app;
144/// ```
145///
146/// # [`InnerPath`] vs `Path`
147/// `Path` gives you every capture in the request path, including those matched by enclosing
148/// [`nest`] calls. [`InnerPath`] gives you only the ones from the route the innermost router
149/// matched. If the router isn't nested, or is nested only at static paths, [`InnerPath`] and `Path` see
150/// exactly the same captures.
151///
152/// # Providing detailed rejection output
153///
154/// If the URI cannot be deserialized into the target type the request will be rejected and an
155/// error response will be returned. See [`customize-path-rejection`] for an example of how to customize that error.
156///
157/// [`serde`]: https://crates.io/crates/serde
158/// [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html
159/// [`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs
160/// [`InnerPath`]: crate::extract::InnerPath
161/// [`nest`]: crate::routing::Router::nest
162#[derive(Debug)]
163pub struct Path<T>(pub T);
164
165axum_core::__impl_deref!(Path);
166
167impl<T, S> FromRequestParts<S> for Path<T>
168where
169    T: DeserializeOwned + Send,
170    S: Send + Sync,
171{
172    type Rejection = PathRejection;
173
174    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
175        get_params(parts).and_then(serialize_path_params).map(Self)
176    }
177}
178
179impl<T, S> OptionalFromRequestParts<S> for Path<T>
180where
181    T: DeserializeOwned + Send + 'static,
182    S: Send + Sync,
183{
184    type Rejection = PathRejection;
185
186    async fn from_request_parts(
187        parts: &mut Parts,
188        _state: &S,
189    ) -> Result<Option<Self>, Self::Rejection> {
190        match parts.extract::<Self>().await {
191            Ok(Self(params)) => Ok(Some(Self(params))),
192            Err(PathRejection::FailedToDeserializePathParams(e)) if e.kind().is_zero_params() => {
193                Ok(None)
194            }
195            Err(e) => Err(e),
196        }
197    }
198}
199
200// this wrapper type is used as the deserializer error to hide the `serde::de::Error` impl which
201// would otherwise be public if we used `ErrorKind` as the error directly
202#[derive(Debug)]
203pub(crate) struct PathDeserializationError {
204    pub(super) kind: ErrorKind,
205}
206
207impl PathDeserializationError {
208    pub(super) fn new(kind: ErrorKind) -> Self {
209        Self { kind }
210    }
211
212    pub(super) fn wrong_number_of_parameters() -> WrongNumberOfParameters<()> {
213        WrongNumberOfParameters { got: () }
214    }
215
216    #[track_caller]
217    pub(super) fn unsupported_type(name: &'static str) -> Self {
218        Self::new(ErrorKind::UnsupportedType { name })
219    }
220}
221
222pub(super) struct WrongNumberOfParameters<G> {
223    got: G,
224}
225
226impl<G> WrongNumberOfParameters<G> {
227    #[allow(clippy::unused_self)]
228    pub(super) fn got<G2>(self, got: G2) -> WrongNumberOfParameters<G2> {
229        WrongNumberOfParameters { got }
230    }
231}
232
233impl WrongNumberOfParameters<usize> {
234    pub(super) fn expected(self, expected: usize) -> PathDeserializationError {
235        PathDeserializationError::new(ErrorKind::WrongNumberOfParameters {
236            got: self.got,
237            expected,
238        })
239    }
240}
241
242impl serde_core::de::Error for PathDeserializationError {
243    #[inline]
244    fn custom<T>(msg: T) -> Self
245    where
246        T: fmt::Display,
247    {
248        Self {
249            kind: ErrorKind::Message(msg.to_string()),
250        }
251    }
252}
253
254impl fmt::Display for PathDeserializationError {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        self.kind.fmt(f)
257    }
258}
259
260impl std::error::Error for PathDeserializationError {}
261
262/// The kinds of errors that can happen we deserializing into a [`Path`].
263///
264/// This type is obtained through [`FailedToDeserializePathParams::kind`] or
265/// [`FailedToDeserializePathParams::into_kind`] and is useful for building
266/// more precise error messages.
267#[must_use]
268#[derive(Debug, PartialEq, Eq)]
269#[non_exhaustive]
270pub enum ErrorKind {
271    /// The URI contained the wrong number of parameters.
272    WrongNumberOfParameters {
273        /// The number of actual parameters in the URI.
274        got: usize,
275        /// The number of expected parameters.
276        expected: usize,
277    },
278
279    /// Failed to parse the value at a specific key into the expected type.
280    ///
281    /// This variant is used when deserializing into types that have named fields, such as structs.
282    ParseErrorAtKey {
283        /// The key at which the value was located.
284        key: String,
285        /// The value from the URI.
286        value: String,
287        /// The expected type of the value.
288        expected_type: &'static str,
289    },
290
291    /// Failed to parse the value at a specific index into the expected type.
292    ///
293    /// This variant is used when deserializing into sequence types, such as tuples.
294    ParseErrorAtIndex {
295        /// The index at which the value was located.
296        index: usize,
297        /// The value from the URI.
298        value: String,
299        /// The expected type of the value.
300        expected_type: &'static str,
301    },
302
303    /// Failed to parse a value into the expected type.
304    ///
305    /// This variant is used when deserializing into a primitive type (such as `String` and `u32`).
306    ParseError {
307        /// The value from the URI.
308        value: String,
309        /// The expected type of the value.
310        expected_type: &'static str,
311    },
312
313    /// A parameter contained text that, once percent decoded, wasn't valid UTF-8.
314    InvalidUtf8InPathParam {
315        /// The key at which the invalid value was located.
316        key: String,
317    },
318
319    /// Tried to serialize into an unsupported type such as nested maps.
320    ///
321    /// This error kind is caused by programmer errors and thus gets converted into a `500 Internal
322    /// Server Error` response.
323    UnsupportedType {
324        /// The name of the unsupported type.
325        name: &'static str,
326    },
327
328    /// Failed to deserialize the value with a custom deserialization error.
329    DeserializeError {
330        /// The key at which the invalid value was located.
331        key: String,
332        /// The value that failed to deserialize.
333        value: String,
334        /// The deserialization failure message.
335        message: String,
336    },
337
338    /// Catch-all variant for errors that don't fit any other variant.
339    Message(String),
340}
341
342impl ErrorKind {
343    fn is_zero_params(&self) -> bool {
344        matches!(&self, Self::WrongNumberOfParameters { got: 0, .. })
345    }
346}
347
348impl fmt::Display for ErrorKind {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        match self {
351            Self::Message(error) => error.fmt(f),
352            Self::InvalidUtf8InPathParam { key } => write!(f, "Invalid UTF-8 in `{key}`"),
353            Self::WrongNumberOfParameters { got, expected } => {
354                write!(
355                    f,
356                    "Wrong number of path arguments for `Path`. Expected {expected} but got {got}"
357                )?;
358
359                if *expected == 1 {
360                    write!(f, ". Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path<YourParams>`")?;
361                }
362
363                Ok(())
364            }
365            Self::UnsupportedType { name } => write!(f, "Unsupported type `{name}`"),
366            Self::ParseErrorAtKey {
367                key,
368                value,
369                expected_type,
370            } => write!(
371                f,
372                "Cannot parse `{key}` with value `{value}` to a `{expected_type}`"
373            ),
374            Self::ParseError {
375                value,
376                expected_type,
377            } => write!(f, "Cannot parse `{value}` to a `{expected_type}`"),
378            Self::ParseErrorAtIndex {
379                index,
380                value,
381                expected_type,
382            } => write!(
383                f,
384                "Cannot parse value at index {index} with value `{value}` to a `{expected_type}`"
385            ),
386            Self::DeserializeError {
387                key,
388                value,
389                message,
390            } => write!(f, "Cannot parse `{key}` with value `{value}`: {message}"),
391        }
392    }
393}
394
395/// Rejection type for [`Path`] if the captured routes params couldn't be deserialized
396/// into the expected type.
397#[derive(Debug)]
398pub struct FailedToDeserializePathParams(PathDeserializationError);
399
400impl FailedToDeserializePathParams {
401    /// Get a reference to the underlying error kind.
402    #[must_use]
403    pub fn kind(&self) -> &ErrorKind {
404        &self.0.kind
405    }
406
407    /// Convert this error into the underlying error kind.
408    pub fn into_kind(self) -> ErrorKind {
409        self.0.kind
410    }
411
412    /// Get the response body text used for this rejection.
413    #[must_use]
414    pub fn body_text(&self) -> String {
415        match self.0.kind {
416            ErrorKind::Message(_)
417            | ErrorKind::DeserializeError { .. }
418            | ErrorKind::InvalidUtf8InPathParam { .. }
419            | ErrorKind::ParseError { .. }
420            | ErrorKind::ParseErrorAtIndex { .. }
421            | ErrorKind::ParseErrorAtKey { .. } => format!("Invalid URL: {}", self.0.kind),
422            ErrorKind::WrongNumberOfParameters { .. } | ErrorKind::UnsupportedType { .. } => {
423                self.0.kind.to_string()
424            }
425        }
426    }
427
428    /// Get the status code used for this rejection.
429    #[must_use]
430    pub fn status(&self) -> StatusCode {
431        match self.0.kind {
432            ErrorKind::Message(_)
433            | ErrorKind::DeserializeError { .. }
434            | ErrorKind::InvalidUtf8InPathParam { .. }
435            | ErrorKind::ParseError { .. }
436            | ErrorKind::ParseErrorAtIndex { .. }
437            | ErrorKind::ParseErrorAtKey { .. } => StatusCode::BAD_REQUEST,
438            ErrorKind::WrongNumberOfParameters { .. } | ErrorKind::UnsupportedType { .. } => {
439                StatusCode::INTERNAL_SERVER_ERROR
440            }
441        }
442    }
443}
444
445impl IntoResponse for FailedToDeserializePathParams {
446    fn into_response(self) -> Response {
447        let body = self.body_text();
448        axum_core::__log_rejection!(
449            rejection_type = Self,
450            body_text = body,
451            status = self.status(),
452        );
453        (self.status(), body).into_response()
454    }
455}
456
457impl fmt::Display for FailedToDeserializePathParams {
458    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459        self.0.fmt(f)
460    }
461}
462
463impl std::error::Error for FailedToDeserializePathParams {}
464
465/// Extractor that will get captures from the URL without deserializing them.
466///
467/// In general you should prefer to use [`Path`] as it is higher level, however `RawPathParams` is
468/// suitable if just want the raw params without deserializing them and thus saving some
469/// allocations.
470///
471/// Any percent encoded parameters will be automatically decoded. The decoded parameters must be
472/// valid UTF-8, otherwise `RawPathParams` will fail and return a `400 Bad Request` response.
473///
474/// # Example
475///
476/// ```rust,no_run
477/// use axum::{
478///     extract::RawPathParams,
479///     routing::get,
480///     Router,
481/// };
482///
483/// async fn users_teams_show(params: RawPathParams) {
484///     for (key, value) in &params {
485///         println!("{key:?} = {value:?}");
486///     }
487/// }
488///
489/// let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show));
490/// # let _: Router = app;
491/// ```
492#[derive(Debug)]
493pub struct RawPathParams(Vec<(Arc<str>, PercentDecodedStr)>);
494
495impl<S> FromRequestParts<S> for RawPathParams
496where
497    S: Send + Sync,
498{
499    type Rejection = RawPathParamsRejection;
500
501    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
502        Self::from_request_extensions(&parts.extensions)
503    }
504}
505
506impl RawPathParams {
507    /// Construct a `RawPathParams<T>` from request extensions.
508    ///
509    /// Most users should prefer to use the `FromRequestParts` impl but special cases may require
510    /// extracting `RawPathParams` outside of an async context.
511    pub fn from_request_extensions(
512        extensions: &Extensions,
513    ) -> Result<Self, RawPathParamsRejection> {
514        match extensions.get::<UrlParams>() {
515            Some(UrlParams::Params { params, .. }) => Ok(Self(params.clone())),
516            Some(UrlParams::InvalidUtf8InPathParam { key }) => Err(InvalidUtf8InPathParam {
517                key: Arc::clone(key),
518            }
519            .into()),
520            None => Err(MissingPathParams.into()),
521        }
522    }
523
524    /// Get an iterator over the path parameters.
525    #[must_use]
526    pub fn iter(&self) -> RawPathParamsIter<'_> {
527        self.into_iter()
528    }
529}
530
531impl<'a> IntoIterator for &'a RawPathParams {
532    type Item = (&'a str, &'a str);
533    type IntoIter = RawPathParamsIter<'a>;
534
535    fn into_iter(self) -> Self::IntoIter {
536        RawPathParamsIter(self.0.iter())
537    }
538}
539
540/// An iterator over raw path parameters.
541///
542/// Created with [`RawPathParams::iter`].
543#[derive(Debug)]
544pub struct RawPathParamsIter<'a>(std::slice::Iter<'a, (Arc<str>, PercentDecodedStr)>);
545
546impl<'a> Iterator for RawPathParamsIter<'a> {
547    type Item = (&'a str, &'a str);
548
549    fn next(&mut self) -> Option<Self::Item> {
550        let (key, value) = self.0.next()?;
551        Some((&**key, value.as_str()))
552    }
553}
554
555/// Rejection used by [`RawPathParams`] if a parameter contained text that, once percent decoded,
556/// wasn't valid UTF-8.
557#[derive(Debug)]
558pub struct InvalidUtf8InPathParam {
559    key: Arc<str>,
560}
561
562impl InvalidUtf8InPathParam {
563    /// Get the response body text used for this rejection.
564    #[must_use]
565    pub fn body_text(&self) -> String {
566        self.to_string()
567    }
568
569    /// Get the status code used for this rejection.
570    #[must_use]
571    pub fn status(&self) -> StatusCode {
572        StatusCode::BAD_REQUEST
573    }
574}
575
576impl fmt::Display for InvalidUtf8InPathParam {
577    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
578        write!(f, "Invalid UTF-8 in `{}`", self.key)
579    }
580}
581
582impl std::error::Error for InvalidUtf8InPathParam {}
583
584impl IntoResponse for InvalidUtf8InPathParam {
585    fn into_response(self) -> Response {
586        let body = self.body_text();
587        axum_core::__log_rejection!(
588            rejection_type = Self,
589            body_text = body,
590            status = self.status(),
591        );
592        (self.status(), body).into_response()
593    }
594}
595
596fn get_params(parts: &Parts) -> Result<&[(Arc<str>, PercentDecodedStr)], PathRejection> {
597    let url_params = parts
598        .extensions
599        .get::<UrlParams>()
600        .ok_or(MissingPathParams)?;
601
602    match url_params {
603        UrlParams::Params { params, .. } => Ok(params),
604        UrlParams::InvalidUtf8InPathParam { key } => {
605            let error = PathDeserializationError {
606                kind: ErrorKind::InvalidUtf8InPathParam {
607                    key: key.to_string(),
608                },
609            };
610            Err(PathRejection::from(FailedToDeserializePathParams(error)))
611        }
612    }
613}
614
615fn serialize_path_params<T, E>(params: &[(Arc<str>, PercentDecodedStr)]) -> Result<T, E>
616where
617    T: DeserializeOwned + Send,
618    E: From<FailedToDeserializePathParams>,
619{
620    let deserializer = de::PathDeserializer::new(params);
621    T::deserialize(deserializer)
622        .map_err(FailedToDeserializePathParams)
623        .map_err(E::from)
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629    use crate::{routing::get, test_helpers::*, Router};
630    use serde::Deserialize;
631    use std::collections::HashMap;
632
633    #[crate::test]
634    async fn extracting_url_params() {
635        let app = Router::new().route(
636            "/users/{id}",
637            get(|Path(id): Path<i32>| async move {
638                assert_eq!(id, 42);
639            })
640            .post(|Path(params_map): Path<HashMap<String, i32>>| async move {
641                assert_eq!(params_map.get("id").unwrap(), &1337);
642            }),
643        );
644
645        let client = TestClient::new(app);
646
647        let res = client.get("/users/42").await;
648        assert_eq!(res.status(), StatusCode::OK);
649
650        let res = client.post("/users/1337").await;
651        assert_eq!(res.status(), StatusCode::OK);
652    }
653
654    #[crate::test]
655    async fn extracting_url_params_multiple_times() {
656        let app = Router::new().route("/users/{id}", get(|_: Path<i32>, _: Path<String>| async {}));
657
658        let client = TestClient::new(app);
659
660        let res = client.get("/users/42").await;
661        assert_eq!(res.status(), StatusCode::OK);
662    }
663
664    #[crate::test]
665    async fn percent_decoding() {
666        let app = Router::new().route(
667            "/{key}",
668            get(|Path(param): Path<String>| async move { param }),
669        );
670
671        let client = TestClient::new(app);
672
673        let res = client.get("/one%20two").await;
674
675        assert_eq!(res.text().await, "one two");
676    }
677
678    #[crate::test]
679    async fn supports_128_bit_numbers() {
680        let app = Router::new()
681            .route(
682                "/i/{key}",
683                get(|Path(param): Path<i128>| async move { param.to_string() }),
684            )
685            .route(
686                "/u/{key}",
687                get(|Path(param): Path<u128>| async move { param.to_string() }),
688            );
689
690        let client = TestClient::new(app);
691
692        let res = client.get("/i/123").await;
693        assert_eq!(res.text().await, "123");
694
695        let res = client.get("/u/123").await;
696        assert_eq!(res.text().await, "123");
697    }
698
699    #[crate::test]
700    async fn wildcard() {
701        let app = Router::new()
702            .route(
703                "/foo/{*rest}",
704                get(|Path(param): Path<String>| async move { param }),
705            )
706            .route(
707                "/bar/{*rest}",
708                get(|Path(params): Path<HashMap<String, String>>| async move {
709                    params.get("rest").unwrap().clone()
710                }),
711            );
712
713        let client = TestClient::new(app);
714
715        let res = client.get("/foo/bar/baz").await;
716        assert_eq!(res.text().await, "bar/baz");
717
718        let res = client.get("/bar/baz/qux").await;
719        assert_eq!(res.text().await, "baz/qux");
720    }
721
722    #[crate::test]
723    async fn captures_dont_match_empty_path() {
724        let app = Router::new().route("/{key}", get(|| async {}));
725
726        let client = TestClient::new(app);
727
728        let res = client.get("/").await;
729        assert_eq!(res.status(), StatusCode::NOT_FOUND);
730
731        let res = client.get("/foo").await;
732        assert_eq!(res.status(), StatusCode::OK);
733    }
734
735    #[crate::test]
736    async fn captures_match_empty_inner_segments() {
737        let app = Router::new().route(
738            "/{key}/method",
739            get(|Path(param): Path<String>| async move { param.clone() }),
740        );
741
742        let client = TestClient::new(app);
743
744        let res = client.get("/abc/method").await;
745        assert_eq!(res.text().await, "abc");
746
747        let res = client.get("//method").await;
748        assert_eq!(res.text().await, "");
749    }
750
751    #[crate::test]
752    async fn captures_match_empty_inner_segments_near_end() {
753        let app = Router::new().route(
754            "/method/{key}/",
755            get(|Path(param): Path<String>| async move { param.clone() }),
756        );
757
758        let client = TestClient::new(app);
759
760        let res = client.get("/method/abc").await;
761        assert_eq!(res.status(), StatusCode::NOT_FOUND);
762
763        let res = client.get("/method/abc/").await;
764        assert_eq!(res.text().await, "abc");
765
766        let res = client.get("/method//").await;
767        assert_eq!(res.text().await, "");
768    }
769
770    #[crate::test]
771    async fn captures_match_empty_trailing_segment() {
772        let app = Router::new().route(
773            "/method/{key}",
774            get(|Path(param): Path<String>| async move { param.clone() }),
775        );
776
777        let client = TestClient::new(app);
778
779        let res = client.get("/method/abc/").await;
780        assert_eq!(res.status(), StatusCode::NOT_FOUND);
781
782        let res = client.get("/method/abc").await;
783        assert_eq!(res.text().await, "abc");
784
785        let res = client.get("/method/").await;
786        assert_eq!(res.text().await, "");
787
788        let res = client.get("/method").await;
789        assert_eq!(res.status(), StatusCode::NOT_FOUND);
790    }
791
792    #[crate::test]
793    async fn str_reference_deserialize() {
794        struct Param(String);
795        impl<'de> serde::Deserialize<'de> for Param {
796            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
797            where
798                D: serde::Deserializer<'de>,
799            {
800                let s = <&str as serde::Deserialize>::deserialize(deserializer)?;
801                Ok(Self(s.to_owned()))
802            }
803        }
804
805        let app = Router::new().route(
806            "/{key}",
807            get(|param: Path<Param>| async move { param.0 .0 }),
808        );
809
810        let client = TestClient::new(app);
811
812        let res = client.get("/foo").await;
813        assert_eq!(res.text().await, "foo");
814
815        // percent decoding should also work
816        let res = client.get("/foo%20bar").await;
817        assert_eq!(res.text().await, "foo bar");
818    }
819
820    #[crate::test]
821    async fn two_path_extractors() {
822        let app = Router::new().route("/{a}/{b}", get(|_: Path<String>, _: Path<String>| async {}));
823
824        let client = TestClient::new(app);
825
826        let res = client.get("/a/b").await;
827        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
828        assert_eq!(
829            res.text().await,
830            "Wrong number of path arguments for `Path`. Expected 1 but got 2. \
831            Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path<YourParams>`",
832        );
833    }
834
835    #[crate::test]
836    async fn tuple_param_matches_exactly() {
837        #[allow(dead_code)]
838        #[derive(Deserialize)]
839        struct Tuple(String, String);
840
841        let app = Router::new()
842            .route(
843                "/foo/{a}/{b}/{c}",
844                get(|_: Path<(String, String)>| async {}),
845            )
846            .route("/bar/{a}/{b}/{c}", get(|_: Path<Tuple>| async {}));
847
848        let client = TestClient::new(app);
849
850        let res = client.get("/foo/a/b/c").await;
851        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
852        assert_eq!(
853            res.text().await,
854            "Wrong number of path arguments for `Path`. Expected 2 but got 3",
855        );
856
857        let res = client.get("/bar/a/b/c").await;
858        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
859        assert_eq!(
860            res.text().await,
861            "Wrong number of path arguments for `Path`. Expected 2 but got 3",
862        );
863    }
864
865    #[crate::test]
866    async fn deserialize_into_vec_of_tuples() {
867        let app = Router::new().route(
868            "/{a}/{b}",
869            get(|Path(params): Path<Vec<(String, String)>>| async move {
870                assert_eq!(
871                    params,
872                    vec![
873                        ("a".to_owned(), "foo".to_owned()),
874                        ("b".to_owned(), "bar".to_owned())
875                    ]
876                );
877            }),
878        );
879
880        let client = TestClient::new(app);
881
882        let res = client.get("/foo/bar").await;
883        assert_eq!(res.status(), StatusCode::OK);
884    }
885
886    #[crate::test]
887    async fn deserialize_into_vec_of_tuples_with_prefixes_and_suffixes() {
888        let app = Router::new().route(
889            "/f{o}o/b{a}r",
890            get(|Path(params): Path<Vec<(String, String)>>| async move {
891                assert_eq!(
892                    params,
893                    vec![
894                        ("o".to_owned(), "0".to_owned()),
895                        ("a".to_owned(), "4".to_owned())
896                    ]
897                );
898            }),
899        );
900
901        let client = TestClient::new(app);
902
903        let res = client.get("/f0o/b4r").await;
904        assert_eq!(res.status(), StatusCode::OK);
905    }
906
907    #[crate::test]
908    async fn type_that_uses_deserialize_any() {
909        use time::Date;
910
911        #[derive(Deserialize)]
912        struct Params {
913            a: Date,
914            b: Date,
915            c: Date,
916        }
917
918        let app = Router::new()
919            .route(
920                "/single/{a}",
921                get(|Path(a): Path<Date>| async move { format!("single: {a}") }),
922            )
923            .route(
924                "/tuple/{a}/{b}/{c}",
925                get(|Path((a, b, c)): Path<(Date, Date, Date)>| async move {
926                    format!("tuple: {a} {b} {c}")
927                }),
928            )
929            .route(
930                "/vec/{a}/{b}/{c}",
931                get(|Path(vec): Path<Vec<Date>>| async move {
932                    let [a, b, c]: [Date; 3] = vec.try_into().unwrap();
933                    format!("vec: {a} {b} {c}")
934                }),
935            )
936            .route(
937                "/vec_pairs/{a}/{b}/{c}",
938                get(|Path(vec): Path<Vec<(String, Date)>>| async move {
939                    let [(_, a), (_, b), (_, c)]: [(String, Date); 3] = vec.try_into().unwrap();
940                    format!("vec_pairs: {a} {b} {c}")
941                }),
942            )
943            .route(
944                "/map/{a}/{b}/{c}",
945                get(|Path(mut map): Path<HashMap<String, Date>>| async move {
946                    let a = map.remove("a").unwrap();
947                    let b = map.remove("b").unwrap();
948                    let c = map.remove("c").unwrap();
949                    format!("map: {a} {b} {c}")
950                }),
951            )
952            .route(
953                "/struct/{a}/{b}/{c}",
954                get(|Path(params): Path<Params>| async move {
955                    format!("struct: {} {} {}", params.a, params.b, params.c)
956                }),
957            );
958
959        let client = TestClient::new(app);
960
961        let res = client.get("/single/2023-01-01").await;
962        assert_eq!(res.text().await, "single: 2023-01-01");
963
964        let res = client.get("/tuple/2023-01-01/2023-01-02/2023-01-03").await;
965        assert_eq!(res.text().await, "tuple: 2023-01-01 2023-01-02 2023-01-03");
966
967        let res = client.get("/vec/2023-01-01/2023-01-02/2023-01-03").await;
968        assert_eq!(res.text().await, "vec: 2023-01-01 2023-01-02 2023-01-03");
969
970        let res = client
971            .get("/vec_pairs/2023-01-01/2023-01-02/2023-01-03")
972            .await;
973        assert_eq!(
974            res.text().await,
975            "vec_pairs: 2023-01-01 2023-01-02 2023-01-03",
976        );
977
978        let res = client.get("/map/2023-01-01/2023-01-02/2023-01-03").await;
979        assert_eq!(res.text().await, "map: 2023-01-01 2023-01-02 2023-01-03");
980
981        let res = client.get("/struct/2023-01-01/2023-01-02/2023-01-03").await;
982        assert_eq!(res.text().await, "struct: 2023-01-01 2023-01-02 2023-01-03");
983    }
984
985    #[crate::test]
986    async fn wrong_number_of_parameters_json() {
987        use serde_json::Value;
988
989        let app = Router::new()
990            .route("/one/{a}", get(|_: Path<(Value, Value)>| async {}))
991            .route("/two/{a}/{b}", get(|_: Path<Value>| async {}));
992
993        let client = TestClient::new(app);
994
995        let res = client.get("/one/1").await;
996        assert!(res
997            .text()
998            .await
999            .starts_with("Wrong number of path arguments for `Path`. Expected 2 but got 1"));
1000
1001        let res = client.get("/two/1/2").await;
1002        assert!(res
1003            .text()
1004            .await
1005            .starts_with("Wrong number of path arguments for `Path`. Expected 1 but got 2"));
1006    }
1007
1008    #[crate::test]
1009    async fn raw_path_params() {
1010        let app = Router::new().route(
1011            "/{a}/{b}/{c}",
1012            get(|params: RawPathParams| async move {
1013                params
1014                    .into_iter()
1015                    .map(|(key, value)| format!("{key}={value}"))
1016                    .collect::<Vec<_>>()
1017                    .join(" ")
1018            }),
1019        );
1020
1021        let client = TestClient::new(app);
1022        let res = client.get("/foo/bar/baz").await;
1023        let body = res.text().await;
1024        assert_eq!(body, "a=foo b=bar c=baz");
1025    }
1026
1027    #[crate::test]
1028    async fn deserialize_error_single_value() {
1029        let app = Router::new().route(
1030            "/resources/{res}",
1031            get(|res: Path<uuid::Uuid>| async move {
1032                let _res = res;
1033            }),
1034        );
1035
1036        let client = TestClient::new(app);
1037        let response = client.get("/resources/123123-123-123123").await;
1038        let body = response.text().await;
1039        assert_eq!(
1040            body,
1041            "Invalid URL: Cannot parse `res` with value `123123-123-123123`: UUID parsing failed: invalid group count: expected 5, found 3"
1042        );
1043    }
1044
1045    #[crate::test]
1046    async fn deserialize_error_multi_value() {
1047        let app = Router::new().route(
1048            "/resources/{res}/sub/{sub}",
1049            get(
1050                |Path((res, sub)): Path<(uuid::Uuid, uuid::Uuid)>| async move {
1051                    let _res = res;
1052                    let _sub = sub;
1053                },
1054            ),
1055        );
1056
1057        let client = TestClient::new(app);
1058        let response = client.get("/resources/456456-123-456456/sub/123").await;
1059        let body = response.text().await;
1060        assert_eq!(
1061            body,
1062            "Invalid URL: Cannot parse `res` with value `456456-123-456456`: UUID parsing failed: invalid group count: expected 5, found 3"
1063        );
1064    }
1065
1066    #[crate::test]
1067    async fn regression_3038() {
1068        #[derive(Deserialize)]
1069        #[allow(dead_code)]
1070        struct MoreChars {
1071            first_two: [char; 2],
1072            second_two: [char; 2],
1073            crate_name: String,
1074        }
1075
1076        let app = Router::new().route(
1077            "/{first_two}/{second_two}/{crate_name}",
1078            get(|Path(_): Path<MoreChars>| async move {}),
1079        );
1080
1081        let client = TestClient::new(app);
1082        let res = client.get("/te/st/_thing").await;
1083        let body = res.text().await;
1084        assert_eq!(body, "Invalid URL: array types are not supported");
1085    }
1086}