Skip to main content

axum/extract/path/
inner_path.rs

1use crate::extract::path::{
2    serialize_path_params, ErrorKind, FailedToDeserializePathParams, PathDeserializationError,
3};
4use crate::extract::rejection::{InnerPathRejection, MissingPathParams};
5use crate::extract::FromRequestParts;
6use crate::routing::url_params::UrlParams;
7use crate::util::PercentDecodedStr;
8use axum_core::extract::OptionalFromRequestParts;
9use axum_core::RequestPartsExt;
10use http::request::Parts;
11use serde_core::de::DeserializeOwned;
12use std::sync::Arc;
13
14/// Extractor that will get captures from the path of the innermost router
15/// and parse them using [`serde`].
16///
17/// Any percent encoded parameters will be automatically decoded. The decoded
18/// parameters must be valid UTF-8, otherwise `InnerPath` will fail and return a `400
19/// Bad Request` response.
20///
21/// # `InnerPath` vs [`Path`]
22/// [`Path`] gives you every capture in the request path, including those matched by enclosing
23/// [`nest`] calls. `InnerPath` gives you only the ones from the route the innermost router
24/// matched. If the router isn't nested, or is nested only at static paths, `InnerPath` and [`Path`] see
25/// exactly the same captures.
26///
27/// # `Option<InnerPath<T>>` behavior
28///
29/// You can use `Option<InnerPath<T>>` as an extractor to allow the same handler to
30/// be used in a route with parameters that deserialize to `T`, and another
31/// route with no parameters at all.
32///
33/// # Example
34///
35/// These examples assume the `serde` feature of the [`uuid`] crate is enabled.
36///
37/// One `InnerPath` can extract multiple captures. It is not necessary (and does
38/// not work) to give a handler more than one `InnerPath` argument.
39///
40/// [`uuid`]: https://crates.io/crates/uuid
41///
42/// ```rust,no_run
43/// use axum::{
44///     extract::InnerPath,
45///     routing::get,
46///     Router,
47/// };
48/// use uuid::Uuid;
49///
50/// async fn user_info(InnerPath(user_id): InnerPath<Uuid>) {
51///     // `user_id` is from the `{user_id}` capture,
52///     // while `{tenant_id}` from the outer router isn't included,
53///     // so this handler works no matter what it's nested under.
54/// }
55///
56/// let api = Router::new().route("/users/{user_id}", get(user_info));
57/// let app = Router::new().nest("/tenants/{tenant_id}", api);
58/// # let _: Router = app;
59/// ```
60///
61/// Captured parameters also can be deserialized into any type that implements
62/// [`serde::Deserialize`]. This includes tuples and structs:
63///
64/// ```rust,no_run
65/// use axum::{
66///     extract::InnerPath,
67///     routing::get,
68///     Router,
69/// };
70/// use serde::Deserialize;
71/// use uuid::Uuid;
72///
73/// #[derive(Deserialize)]
74/// struct Params {
75///     user_id: Uuid,
76///     team_id: Uuid,
77/// }
78///
79/// async fn users_teams_show(
80///     InnerPath(Params { user_id, team_id }): InnerPath<Params>,
81/// ) {
82///     // Capture parameters will be matched by struct field names
83/// }
84///
85/// async fn users_teams_create(
86///     InnerPath((user_id, team_id)): InnerPath<(String, String)>,
87/// ) {
88///     // When using tuples captures will be matched by their position in the route
89/// }
90///
91/// let api = Router::new().route(
92///     "/users/{user_id}/team/{team_id}",
93///     get(users_teams_show).post(users_teams_create)
94/// );
95/// let app = Router::new().nest("/tenants/{tenant_id}", api);
96/// # let _: Router = app;
97/// ```
98///
99/// If you wish to capture all inner path parameters you can use `HashMap` or `Vec`:
100///
101/// ```rust,no_run
102/// use axum::{
103///     extract::InnerPath,
104///     routing::get,
105///     Router,
106/// };
107/// use std::collections::HashMap;
108///
109/// async fn params_map(
110///     InnerPath(params): InnerPath<HashMap<String, String>>,
111/// ) {
112///     // `params` contains keys "user_id" and "team_id"
113/// }
114///
115/// async fn params_vec(
116///     InnerPath(params): InnerPath<Vec<(String, String)>>,
117/// ) {
118///     // `params` contains one tuple for `user_id` and one for `team_id`
119/// }
120///
121/// let api = Router::new()
122///     .route("/users/{user_id}/team/{team_id}", get(params_map).post(params_vec));
123/// let app = Router::new().nest("/tenants/{tenant_id}", api);
124/// # let _: Router = app;
125/// ```
126///
127/// # Providing detailed rejection output
128///
129/// If the URI cannot be deserialized into the target type the request will be rejected and an
130/// error response will be returned. See [`customize-path-rejection`] for an example of how to customize that error.
131///
132/// [`serde`]: https://crates.io/crates/serde
133/// [`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html
134/// [`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs
135/// [`Path`]: crate::extract::Path
136/// [`nest`]: crate::routing::Router::nest
137#[derive(Debug)]
138pub struct InnerPath<T>(pub T);
139
140axum_core::__impl_deref!(InnerPath);
141
142impl<T, S> FromRequestParts<S> for InnerPath<T>
143where
144    T: DeserializeOwned + Send,
145    S: Send + Sync,
146{
147    type Rejection = InnerPathRejection;
148
149    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
150        get_inner_params(parts)
151            .and_then(serialize_path_params)
152            .map(Self)
153    }
154}
155
156impl<T, S> OptionalFromRequestParts<S> for InnerPath<T>
157where
158    T: DeserializeOwned + Send + 'static,
159    S: Send + Sync,
160{
161    type Rejection = InnerPathRejection;
162
163    async fn from_request_parts(
164        parts: &mut Parts,
165        _state: &S,
166    ) -> Result<Option<Self>, Self::Rejection> {
167        match parts.extract::<Self>().await {
168            Ok(Self(params)) => Ok(Some(Self(params))),
169            Err(InnerPathRejection::FailedToDeserializePathParams(e))
170                if e.kind().is_zero_params() =>
171            {
172                Ok(None)
173            }
174            Err(e) => Err(e),
175        }
176    }
177}
178
179fn get_inner_params(parts: &Parts) -> Result<&[(Arc<str>, PercentDecodedStr)], InnerPathRejection> {
180    let url_params = parts
181        .extensions
182        .get::<UrlParams>()
183        .ok_or(MissingPathParams)?;
184
185    match url_params {
186        UrlParams::Params {
187            params,
188            inner_start,
189        } => {
190            let inner_params = params
191                .get(*inner_start..)
192                .expect("Mismatch between url params and count of captures. This is bug in axum. Please file an issue.");
193
194            Ok(inner_params)
195        }
196        UrlParams::InvalidUtf8InPathParam { key } => {
197            let error = PathDeserializationError {
198                kind: ErrorKind::InvalidUtf8InPathParam {
199                    key: key.to_string(),
200                },
201            };
202            Err(InnerPathRejection::from(FailedToDeserializePathParams(
203                error,
204            )))
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use crate::{
213        extract::{Path, Request},
214        middleware::{from_fn, Next},
215        routing::get,
216        test_helpers::*,
217        Router,
218    };
219    use axum_core::response::Response;
220    use http::StatusCode;
221    use std::collections::HashMap;
222
223    type Params = Vec<(String, String)>;
224
225    fn params(pairs: &[(&str, &str)]) -> Params {
226        pairs
227            .iter()
228            .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
229            .collect()
230    }
231
232    #[crate::test]
233    async fn without_nesting_matches_path() {
234        let app = Router::new().route(
235            "/users/{user_id}/team/{team_id}",
236            get(
237                |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
238                    let expected = params(&[("user_id", "42"), ("team_id", "1337")]);
239                    assert_eq!(all, expected);
240                    assert_eq!(inner, expected);
241                    assert_eq!(inner, all);
242                    "teams#show"
243                },
244            ),
245        );
246        let res = TestClient::new(app).get("/users/42/team/1337").await;
247
248        assert_eq!(res.status(), StatusCode::OK);
249        assert_eq!(res.text().await, "teams#show");
250    }
251
252    #[crate::test]
253    async fn static_nest_prefix_contributes_nothing() {
254        let app = Router::new().nest(
255            "/api",
256            Router::new().route(
257                "/users/{user_id}",
258                get(
259                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
260                        let expected = params(&[("user_id", "42")]);
261                        assert_eq!(all, expected);
262                        assert_eq!(inner, expected);
263                        assert_eq!(inner, all);
264                        "users#show"
265                    },
266                ),
267            ),
268        );
269        let res = TestClient::new(app).get("/api/users/42").await;
270
271        assert_eq!(res.status(), StatusCode::OK);
272        assert_eq!(res.text().await, "users#show");
273    }
274
275    #[crate::test]
276    async fn dynamic_nest_prefix_is_excluded() {
277        let app = Router::new().nest(
278            "/org/{org}",
279            Router::new().route(
280                "/team/{team_id}",
281                get(
282                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
283                        assert_eq!(all, params(&[("org", "acme"), ("team_id", "1337")]));
284                        assert_eq!(inner, params(&[("team_id", "1337")]));
285                        "teams#show"
286                    },
287                ),
288            ),
289        );
290        let res = TestClient::new(app).get("/org/acme/team/1337").await;
291
292        assert_eq!(res.status(), StatusCode::OK);
293        assert_eq!(res.text().await, "teams#show");
294    }
295
296    #[crate::test]
297    async fn nesting_mixing_static_and_dynamic_levels() {
298        let app = Router::new().nest(
299            "/api",
300            Router::new().nest(
301                "/{version}",
302                Router::new().nest(
303                    "/admin",
304                    Router::new().route(
305                        "/{id}",
306                        get(
307                            |Path(all): Path<Params>,
308                             InnerPath(inner): InnerPath<Params>| async move {
309                                assert_eq!(all, params(&[("version", "v2"), ("id", "42")]));
310                                assert_eq!(inner, params(&[("id", "42")]));
311                                "admin#show"
312                            },
313                        ),
314                    ),
315                ),
316            ),
317        );
318        let res = TestClient::new(app).get("/api/v2/admin/42").await;
319
320        assert_eq!(res.status(), StatusCode::OK);
321        assert_eq!(res.text().await, "admin#show");
322    }
323
324    #[crate::test]
325    async fn offset_sums_captures_across_levels() {
326        let app = Router::new().nest(
327            "/{prefix_one}",
328            Router::new().nest(
329                "/{prefix_two}/{prefix_three}",
330                Router::new().nest(
331                    "/x/{prefix_four}",
332                    Router::new().route(
333                        "/{leaf_one}/{leaf_two}",
334                        get(
335                            |Path(all): Path<Params>,
336                             InnerPath(inner): InnerPath<Params>| async move {
337                                assert_eq!(
338                                    all,
339                                    params(&[
340                                        ("prefix_one", "1"),
341                                        ("prefix_two", "2"),
342                                        ("prefix_three", "3"),
343                                        ("prefix_four", "4"),
344                                        ("leaf_one", "5"),
345                                        ("leaf_two", "6"),
346                                    ])
347                                );
348                                assert_eq!(
349                                    inner,
350                                    params(&[("leaf_one", "5"), ("leaf_two", "6")])
351                                );
352                                "leaf"
353                            },
354                        ),
355                    ),
356                ),
357            ),
358        );
359        let res = TestClient::new(app).get("/1/2/3/x/4/5/6").await;
360
361        assert_eq!(res.status(), StatusCode::OK);
362        assert_eq!(res.text().await, "leaf");
363    }
364
365    // `#[crate::test]` generates extra tests where `nest` calls are converted to `nest_service`.
366    // This test mixes `nest` and `nest_service` at different levels.
367    #[crate::test]
368    async fn outer_nest_with_inner_nest_service() {
369        let app = Router::new().nest(
370            "/api",
371            Router::new().nest_service(
372                "/{version}",
373                Router::new().route(
374                    "/{id}",
375                    get(
376                        |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
377                            assert_eq!(all, params(&[("version", "v2"), ("id", "42")]));
378                            assert_eq!(inner, params(&[("id", "42")]));
379                            "items#show"
380                        },
381                    ),
382                ),
383            ),
384        );
385        let res = TestClient::new(app).get("/api/v2/42").await;
386
387        assert_eq!(res.status(), StatusCode::OK);
388        assert_eq!(res.text().await, "items#show");
389    }
390
391    #[crate::test]
392    async fn wildcard() {
393        let app = Router::new().nest(
394            "/org/{org}",
395            Router::new().route(
396                "/files/{*rest}",
397                get(
398                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
399                        assert_eq!(all, params(&[("org", "acme"), ("rest", "a/b/c")]));
400                        assert_eq!(inner, params(&[("rest", "a/b/c")]));
401                        "files#show"
402                    },
403                ),
404            ),
405        );
406        let res = TestClient::new(app).get("/org/acme/files/a/b/c").await;
407
408        assert_eq!(res.status(), StatusCode::OK);
409        assert_eq!(res.text().await, "files#show");
410    }
411
412    #[crate::test]
413    async fn inner_route_without_captures() {
414        let app = Router::new().nest(
415            "/org/{org}",
416            Router::new().route(
417                "/static",
418                get(
419                    |Path(all): Path<Params>,
420                     InnerPath(inner): InnerPath<Params>,
421                     opt: Option<InnerPath<String>>| async move {
422                        assert_eq!(all, params(&[("org", "acme")]));
423                        assert_eq!(inner, params(&[]));
424                        assert_eq!(opt.as_deref(), None);
425                        "static"
426                    },
427                ),
428            ),
429        );
430        let res = TestClient::new(app).get("/org/acme/static").await;
431
432        assert_eq!(res.status(), StatusCode::OK);
433        assert_eq!(res.text().await, "static");
434    }
435
436    #[crate::test]
437    async fn hash_map_only_contains_inner_captures() {
438        let app = Router::new().nest(
439            "/org/{org}",
440            Router::new().route(
441                "/team/{team_id}",
442                get(
443                    |Path(all): Path<HashMap<String, String>>,
444                     InnerPath(inner): InnerPath<HashMap<String, String>>| async move {
445                        assert_eq!(
446                            all,
447                            HashMap::from_iter(params(&[("org", "acme"), ("team_id", "1337")]))
448                        );
449                        assert_eq!(inner, HashMap::from_iter(params(&[("team_id", "1337")])));
450                        "teams#show"
451                    },
452                ),
453            ),
454        );
455        let res = TestClient::new(app).get("/org/acme/team/1337").await;
456
457        assert_eq!(res.status(), StatusCode::OK);
458        assert_eq!(res.text().await, "teams#show");
459    }
460
461    #[crate::test]
462    async fn same_router_nested_at_prefixes_of_different_arity() {
463        fn resources() -> Router {
464            Router::new().route(
465                "/{id}/{version}",
466                get(|InnerPath(inner): InnerPath<Params>| async move {
467                    assert_eq!(inner, params(&[("id", "thing"), ("version", "3")]));
468                    "resources#show"
469                }),
470            )
471        }
472
473        let app = Router::new()
474            .nest("/global/{env}", resources())
475            .nest("/customer/{customer_id}/{env}", resources());
476        let client = TestClient::new(app);
477
478        let res = client.get("/global/prod/thing/3").await;
479        assert_eq!(res.status(), StatusCode::OK);
480        assert_eq!(res.text().await, "resources#show");
481
482        let res = client.get("/customer/acme/prod/thing/3").await;
483        assert_eq!(res.status(), StatusCode::OK);
484        assert_eq!(res.text().await, "resources#show");
485    }
486
487    #[crate::test]
488    async fn in_nested_fallback() {
489        let app = Router::new().nest(
490            "/org/{org}",
491            Router::new().fallback(get(
492                |Path(all): Path<Params>,
493                 InnerPath(inner): InnerPath<Params>,
494                 opt: Option<InnerPath<String>>| async move {
495                    assert_eq!(all, params(&[("org", "acme")]));
496                    assert_eq!(inner, params(&[]));
497                    assert_eq!(opt.as_deref(), None);
498                    "fallback"
499                },
500            )),
501        );
502        let res = TestClient::new(app).get("/org/acme/does-not-exist").await;
503
504        assert_eq!(res.status(), StatusCode::OK);
505        assert_eq!(res.text().await, "fallback");
506    }
507
508    #[crate::test]
509    async fn in_nested_middleware() {
510        async fn middleware(
511            Path(all): Path<Params>,
512            InnerPath(inner): InnerPath<Params>,
513            req: Request,
514            next: Next,
515        ) -> Response {
516            assert_eq!(all, params(&[("org", "acme"), ("team_id", "1337")]));
517            assert_eq!(inner, params(&[("team_id", "1337")]));
518            next.run(req).await
519        }
520
521        let app = Router::new().nest(
522            "/org/{org}",
523            Router::new()
524                .route("/team/{team_id}", get(|| async { "teams#show" }))
525                .layer(from_fn(middleware)),
526        );
527        let res = TestClient::new(app).get("/org/acme/team/1337").await;
528
529        assert_eq!(res.status(), StatusCode::OK);
530        assert_eq!(res.text().await, "teams#show");
531    }
532
533    #[crate::test]
534    async fn merge_preserves_per_route_offsets() {
535        let unnested = Router::new().route(
536            "/plain/{id}",
537            get(
538                |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
539                    let expected = params(&[("id", "0")]);
540                    assert_eq!(all, expected);
541                    assert_eq!(inner, expected);
542                    "unnested"
543                },
544            ),
545        );
546
547        let nested_under_one_capture = Router::new().nest(
548            "/org/{org}",
549            Router::new().route(
550                "/{id}",
551                get(
552                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
553                        assert_eq!(all, params(&[("org", "acme"), ("id", "1")]));
554                        assert_eq!(inner, params(&[("id", "1")]));
555                        "nested_under_one_capture"
556                    },
557                ),
558            ),
559        );
560
561        let nested_under_two_captures = Router::new().nest(
562            "/team/{team}/{env}",
563            Router::new().route(
564                "/{id}",
565                get(
566                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
567                        assert_eq!(
568                            all,
569                            params(&[("team", "blue"), ("env", "prod"), ("id", "2")])
570                        );
571                        assert_eq!(inner, params(&[("id", "2")]));
572                        "nested_under_two_captures"
573                    },
574                ),
575            ),
576        );
577
578        let client = TestClient::new(
579            unnested
580                .merge(nested_under_one_capture)
581                .merge(nested_under_two_captures),
582        );
583
584        let res = client.get("/plain/0").await;
585        assert_eq!(res.status(), StatusCode::OK);
586        assert_eq!(res.text().await, "unnested");
587
588        let res = client.get("/org/acme/1").await;
589        assert_eq!(res.status(), StatusCode::OK);
590        assert_eq!(res.text().await, "nested_under_one_capture");
591
592        let res = client.get("/team/blue/prod/2").await;
593        assert_eq!(res.status(), StatusCode::OK);
594        assert_eq!(res.text().await, "nested_under_two_captures");
595    }
596
597    #[crate::test]
598    async fn nesting_a_merged_router_composes_offsets() {
599        let already_nested = Router::new().nest(
600            "/org/{org}",
601            Router::new().route(
602                "/{id}",
603                get(
604                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
605                        assert_eq!(all, params(&[("v", "2"), ("org", "acme"), ("id", "1")]));
606                        assert_eq!(inner, params(&[("id", "1")]));
607                        "already_nested"
608                    },
609                ),
610            ),
611        );
612
613        let not_yet_nested = Router::new().route(
614            "/plain/{id}",
615            get(
616                |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
617                    assert_eq!(all, params(&[("v", "2"), ("id", "0")]));
618                    assert_eq!(inner, params(&[("id", "0")]));
619                    "not_yet_nested"
620                },
621            ),
622        );
623
624        let app = Router::new().nest("/api/{v}", already_nested.merge(not_yet_nested));
625        let client = TestClient::new(app);
626
627        let res = client.get("/api/2/org/acme/1").await;
628        assert_eq!(res.status(), StatusCode::OK);
629        assert_eq!(res.text().await, "already_nested");
630
631        let res = client.get("/api/2/plain/0").await;
632        assert_eq!(res.status(), StatusCode::OK);
633        assert_eq!(res.text().await, "not_yet_nested");
634    }
635
636    #[crate::test]
637    async fn percent_decoding_still_applies() {
638        let app = Router::new().nest(
639            "/org/{org}",
640            Router::new().route(
641                "/{name}",
642                get(
643                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
644                        assert_eq!(all, params(&[("org", "acme"), ("name", "one two")]));
645                        assert_eq!(inner, params(&[("name", "one two")]));
646                        "names#show"
647                    },
648                ),
649            ),
650        );
651        let res = TestClient::new(app).get("/org/acme/one%20two").await;
652
653        assert_eq!(res.status(), StatusCode::OK);
654        assert_eq!(res.text().await, "names#show");
655    }
656
657    #[crate::test]
658    async fn wrong_number_of_parameters_is_rejected() {
659        let app = Router::new().nest(
660            "/org/{org}",
661            Router::new().route("/{id}", get(|_: InnerPath<(u32, u32)>| async move {})),
662        );
663        let res = TestClient::new(app).get("/org/acme/42").await;
664
665        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
666        assert_eq!(
667            res.text().await,
668            "Wrong number of path arguments for `Path`. Expected 2 but got 1"
669        );
670    }
671
672    #[crate::test]
673    async fn duplicate_capture_names_across_levels() {
674        let app = Router::new().nest(
675            "/org/{id}",
676            Router::new().route(
677                "/{id}",
678                get(
679                    |Path(all): Path<Params>, InnerPath(inner): InnerPath<Params>| async move {
680                        assert_eq!(all, params(&[("id", "outer"), ("id", "inner")]));
681                        assert_eq!(inner, params(&[("id", "inner")]));
682                        "items#show"
683                    },
684                ),
685            ),
686        );
687        let res = TestClient::new(app).get("/org/outer/inner").await;
688
689        assert_eq!(res.status(), StatusCode::OK);
690        assert_eq!(res.text().await, "items#show");
691    }
692
693    #[crate::test]
694    async fn invalid_utf8_in_nest_prefix_capture() {
695        let app = Router::new().nest(
696            "/org/{org}",
697            Router::new().route(
698                "/team/{team_id}",
699                get(|_: InnerPath<Params>| async move { "teams#show" }),
700            ),
701        );
702        let res = TestClient::new(app).get("/org/%FF/team/1337").await;
703
704        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
705        assert_eq!(res.text().await, "Invalid URL: Invalid UTF-8 in `org`");
706    }
707
708    #[crate::test]
709    async fn invalid_utf8_in_inner_capture() {
710        let app = Router::new().nest(
711            "/org/{org}",
712            Router::new().route(
713                "/team/{team_id}",
714                get(|_: InnerPath<Params>| async move { "teams#show" }),
715            ),
716        );
717        let res = TestClient::new(app).get("/org/acme/team/%FF").await;
718
719        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
720        assert_eq!(res.text().await, "Invalid URL: Invalid UTF-8 in `team_id`");
721    }
722}