Expand description
§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::{Json, State};
use axum_typed_routing::{route, TypedRouter};
#[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, OperationInput};
use axum::extract::{Json, State};
use axum_typed_routing::TypedApiRouter;
use axum_typed_routing_macros::api_route;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[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: String,
) -> String {
todo!("handle request")
}
fn main() {
let router: ApiRouter = ApiRouter::new()
.typed_api_route(item_handler)
.with_state("state".to_string());
}
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct Integer(pub u32);
impl OperationInput for Integer {}Traits§
- Typed
ApiRouter - Same as
TypedRouter, but with support foraide. - Typed
Router - A trait that allows typed routes, created with the
routemacro to be added to an axum router.