#[axum]Expand description
The openapi_trait attribute macro, wired to the axum backend.
Re-exported from openapi_trait_axum. Apply it to a mod block with a
path to an OpenAPI YAML or JSON file. The path is resolved relative to
CARGO_MANIFEST_DIR.
Generates typed Rust code from an OpenAPI specification file.
Apply this attribute to a mod block. The macro reads the OpenAPI
document at the given path (resolved relative to CARGO_MANIFEST_DIR) at
compile time and replaces the module’s contents with:
- Schema structs derived from
components/schemas - A
{OperationId}Requeststruct per operation (bundles path, query, header params and the request body) - Per-operation
{OperationId}Responseenums implementingaxum::response::IntoResponse - A
{Title}Apitrait with oneasync fnper operation (keyed byoperationId). Trait methods have a default implementation that returns500 Internal Server Error, so you only need to override the operations your server handles. - A
routermethod on the trait that wires all operations to anaxum::Router
The crate recompiles automatically whenever the spec file changes.
§Arguments
First positional argument: path to the OpenAPI YAML or JSON file,
relative to the crate root (CARGO_MANIFEST_DIR).
§Examples
ⓘ
#[openapi_trait::axum("openapi/petstore.yaml")]
pub mod petstore {}
#[derive(Clone)]
struct MyServer;
impl petstore::PetstoreApi for MyServer {
type Error = std::convert::Infallible;
async fn get_pet_by_id(
&self,
req: petstore::GetPetByIdRequest,
_state: axum::extract::State<()>,
_headers: axum::http::HeaderMap,
) -> Result<petstore::GetPetByIdResponse, Self::Error> {
Ok(petstore::GetPetByIdResponse::Status200(petstore::Pet {
id: Some(req.pet_id),
name: "doggie".into(),
photo_urls: vec![],
category: None,
tags: None,
status: None,
}))
}
}
let app = MyServer.router().with_state(());§Errors
The macro emits a compile error if:
- The file cannot be found or read.
- The
OpenAPIdocument is malformed or cannot be parsed. - An operation is missing an
operationId.