Skip to content

Routing

A route processes incoming requests for a given method and path pattern. Pavex takes care, at runtime, of routing incoming requests to the most appropriate route.

As your application grows, you may benefit from Pavex's more advanced routing features:

  • Fallbacks, to customize the response returned when no route matches.
  • Path prefixes, to reduce repetition in your route definitions.
  • Domain guards, to serve different content based on the domain being requested.

Defining a route

Pavex provides attributes for the most common HTTP methods: #[get], #[post], #[put], #[patch], #[delete], #[head], and #[options].

use pavex::Response;
use pavex::get;
use pavex::request::path::PathParams;

#[PathParams]
pub struct Info {
    pub first_name: String,
    pub last_name: String,
}

#[get(path = "/greet/{first_name}/{last_name}")]
pub fn formal_greet(info: PathParams<Info>) -> Response {
    let body = format!("Hello, {} {}!", info.0.first_name, info.0.last_name);
    Response::ok().set_typed_body(body)
}

Use #[route], instead, to define routes that match multiple methods, non-standard methods or arbitrary methods.

Requirements

Routes must return, as output, a type that implements the IntoResponse trait.
Routes can fail, too. A fallible route will return Result<T, E>, where T implements IntoResponse and E is an error type.

Other than that, you have a lot of freedom in how you define your routes:

Registration

Use Blueprint::routes to register in bulk all the routes defined in the current crate:

use pavex::{Blueprint, blueprint::from};

pub fn blueprint() -> Blueprint {
    let mut bp = Blueprint::new();
    bp.routes(from![crate]); // (1)!
    // [...]
}
  1. You can also import routes from other crates or specific modules.

Alternatively, register routes one by one using Blueprint::route:

use pavex::Blueprint;

use crate::multiple_named_parameters::FORMAL_GREET;

pub fn blueprint() -> Blueprint {
    let mut bp = Blueprint::new();
    bp.route(FORMAL_GREET); // (1)!
    // [...]
}
  1. FORMAL_GREET is a strongly-typed constant generated by the #[get] attribute on the formal_greet function.
    Check out the documentation on component ids for more details.

Position matters

Be careful when registering routes: their position relative to middlewares and error observers determines if they are affected by them, or not.