Skip to content

On functions and methods

Most1 Pavex attributes must applied to a function or a method—something that can be invoked.

Free functions

For free functions, it's as easy as it gets: the attribute goes on top of the function definition.

use pavex::Response;
use pavex::get;

#[get(path = "/")] // (1)!
pub fn landing_page() -> Response {
    // [...]
}
  1. This function, annotated with #[pavex::get], will handle GET / requests.

Methods

Methods require an extra bit of syntax: you must add #[pavex::methods] to the impl block where the annotated method is defined.

use pavex::Response;
use pavex::methods;

pub struct AuthError {
    // [...]
}

#[methods] // (1)!
impl AuthError {
    #[error_handler]
    pub fn to_response(&self) -> Response {
        // [...]
    }
}
  1. The #[pavex::methods] attribute is right on top of the impl block.

Pavex will raise an error at compile-time if you forget #[pavex::methods].

Trait methods

You can also use trait methods as Pavex components:

use pavex::methods;

pub struct RequestId(uuid::Uuid);

#[methods] // (1)!
impl Default for RequestId {
    #[request_scoped]
    fn default() -> Self {
        Self(uuid::Uuid::now_v7())
    }
}
  1. The #[pavex::methods] attribute is on top of the impl block, identical to the previous example.

  1. All attributes with the exception of #[pavex::config] and #[pavex::prebuilt], which are covered in the next section on type annotations