Attribute Macro route

Source
#[route]
Expand description

A macro that generates statically-typed routes for axum handlers.

§Syntax

#[route(<METHOD> "<PATH>" [with <STATE>])]
  • METHOD is the HTTP method, such as GET, POST, PUT, etc.
  • PATH is the path of the route, with optional path parameters and query parameters, e.g. /item/:id?amount&offset.
  • STATE is the type of axum-state, passed to the handler. This is optional, and if not specified, the state type is guessed based on the parameters of the handler.

§Example

use axum::extract::{State, Json};
use axum_typed_routing_macros::route;

#[route(GET "/item/:id?amount&offset")]
async fn item_handler(
    id: u32,
    amount: Option<u32>,
    offset: Option<u32>,
    State(state): State<String>,
    Json(json): Json<u32>,
) -> String {
    todo!("handle request")
}

§State type

Normally, the state-type is guessed based on the parameters of the function: If the function has a parameter of type [..]::State<T>, then T is used as the state type. This should work for most cases, however when not sufficient, the state type can be specified explicitly using the with keyword:

#[route(GET "/item/:id?amount&offset" with String)]

§Internals

The macro expands to a function with signature fn() -> (&'static str, axum::routing::MethodRouter<S>). The first element of the tuple is the path, and the second is axum’s MethodRouter.

The path and query are extracted using axum’s extract::Path and extract::Query extractors, as the first and second parameters of the function. The remaining parameters are the parameters of the handler.