Expand description

Crates.io Documentation

§Axum-typed-routing

A library for creating statically-typed handlers in axum using macros, similar to Rocket with OpenAPI support using aide.

See the docs for more information.

§Basic usage

The following example demonstrates the basic usage of the library. On top of any regular handler, you can add the route macro to create a typed route. Any path- or query-parameters in the url will be type-checked at compile-time, and properly extracted into the handler.

The following example shows how the path parameter id, and query parameters amount and offset are type-checked and extracted into the handler.

#![allow(unused)]
use axum::extract::{State, Json};
use axum_typed_routing::{TypedRouter, 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")
}

fn main() {
    let router: axum::Router = axum::Router::new()
        .typed_route(item_handler)
        .with_state("state".to_string());
}

Some valid url’s as get-methods are:

  • /item/1?amount=2&offset=3
  • /item/1?amount=2
  • /item/1?offset=3
  • /item/500

By marking the amount and offset parameters as Option<T>, they become optional.

§Example with aide

When the aide feature is enabled, it’s possible to automatically generate OpenAPI documentation for the routes. The api_route macro is used in place of the route macro.

Please read the aide documentation for more information on usage.

#![allow(unused)]
use aide::axum::ApiRouter;
use axum::extract::{Json, State};
use axum_typed_routing::TypedApiRouter;
use axum_typed_routing_macros::api_route;

#[api_route(GET "/item/:id?amount&offset" {
    summary: "Get an item",
    description: "Get an item by id",
    id: "get-item",
    tags: ["items"],
    hidden: false
})]
async fn item_handler(
    id: u32,
    amount: Option<u32>,
    offset: Option<u32>,
    State(state): State<String>,
    Json(json): Json<u32>,
) -> String {
    todo!("handle request")
}

fn main() {
    let router: ApiRouter = ApiRouter::new()
        .typed_api_route(item_handler)
        .with_state("state".to_string());
}

Traits§

Attribute Macros§

  • Same as route, but with support for OpenApi using aide. See route for more information and examples.
  • A macro that generates statically-typed routes for axum handlers.