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 argument attributes:

  • handlers(...) List of method references having attribute #[utoipa::path] macro.
  • components(...) List of Components in OpenAPI schema.
  • modifiers(...) List of items implemeting Modify trait for runtime OpenApi modification. See the trait documentation for more details.
  • security(...) List of SecurityRequirements global to all operations. See more details in #[utoipa::path(...)] attribute macro security options.
  • tags(...) List of Tag which must match the tag path operation. By default the tag is derived from path given to handlers list or if undefined then crate is used by default. Alternatively the tag name can be given to path operation via #[utoipa::path(...)] macro. Tag can be used to define extra information for the api to produce richer documentation.
  • external_docs(...) Can be used to reference external resource to the OpenAPI doc for extended documentation. External docs can be in OpenApi or in Tag level.

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 license

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),
    security(
        (),
        ("my_auth" = ["read:items", "edit:items"]),
        ("token_jwt" = [])
    ),
    tags(
        (name = "pets::api", description = "All about pets",
            external_docs(url = "http://more.about.pets.api", description = "Find out more"))
    ),
    external_docs(url = "http://more.about.our.apis", description = "More about our APIs")
)]
struct ApiDoc;