Derive Macro utoipa::OpenApi

source · []
#[derive(OpenApi)]
{
    // Attributes available to this derive:
    #[openapi]
}
Expand description

OpenApi derive macro

This is #[derive] implementation for OpenApi trait. The macro accepts one openapi argument.

Accepted openapi argument attributes

  • handlers List of method references having attribute #[utoipa::path] macro.
  • components List of Components in OpenAPI schema.

OpenApi derive macro will also derive Info for OpenApi specification using Cargo environment variables.

  • env CARGO_PKG_NAME map to info title
  • env CARGO_PKG_VERSION map to info version
  • env CARGO_PKG_DESCRIPTION map info description
  • env CARGO_PKG_AUTHORS map to contact name and email only first author will be used
  • env CARGO_PKG_LICENSE map to info licence

Examples

Define OpenApi schema with some paths and components.

#[derive(Component)]
struct Pet {
    name: String,
    age: i32,
}

#[derive(Component)]
enum Status {
    Active, InActive, Locked,
}

#[utoipa::path(get, path = "/pet")]
fn get_pet() - Pet {
    Pet {
        name: "bob".to_string(),
        age: 8,
    }
}

#[utoipa::path(get, path = "/status")]
fn get_status() - Status {
    Status::Active
}

#[derive(OpenApi)]
#[openapi(handlers = [get_pet, get_status], components = [Pet, Status])]
struct ApiDoc;