Skip to main content

openapi_trait

Attribute Macro openapi_trait 

Source
#[openapi_trait]
Expand description

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}Request struct per operation (bundles path, query, header params and the request body)
  • Per-operation {OperationId}Response enums implementing axum::response::IntoResponse
  • A {ModName}Api<S = ()> trait with one async fn per operation (keyed by operationId). Trait methods have a default implementation that returns 500 Internal Server Error, so you only need to override the operations your server handles.
  • A router method on the trait that wires all operations to an axum::Router

The generated trait name is derived from the annotated module name, so mod petstore {} produces petstore::PetstoreApi.

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).

§Errors

The macro emits a compile error if:

  • The file cannot be found or read.
  • The OpenAPI document is malformed or cannot be parsed.
  • An operation is missing an operationId.