Derive Macro utoipa::Component

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

Component dervice macro

This is #[derive] implementation for Component trait. The macro accepts one component attribute optionally which can be used to enhance generated documentation. The attribute can be placed at item level or field level in struct and enums. Currently placing this attribute to unnamed field does not have any effect.

Struct Optional Configuration Options

  • example Can be either json!(...) or literal string that can be parsed to json. json! should be something that serde_json::json! can parse as a serde_json::Value. 1

Enum & Unnamed Field Struct Optional Configuration Options

  • example Can be method reference or literal value. 2
  • default Can be method reference or literal value. 2

Named Fields Optional Configuration Options

  • example Can be method reference or literal value. 2
  • default Can be method reference or literal value. 2
  • format ComponentFormat to use for the property. By default the format is derived from the type of the property according OpenApi spec.
  • write_only Defines property is only used in write operations POST,PUT,PATCH but not in GET
  • read_only Defines property is only used in read operations GET but not in POST,PUT,PATCH

Examples

Example struct with struct level example.

#[derive(Component)]
#[component(example = json!({"name": "bob the cat", "id": 0}))]
struct Pet {
    id: u64,
    name: String,
    age: Option<i32>,
}

The component attribute can also be placed at field level as follows.

#[derive(Component)]
struct Pet {
    #[component(example = 1, default = 0))]
    id: u64,
    name: String,
    age: Option<i32>,
}

You can also use method reference for attribute values.

#[derive(Component)]
struct Pet {
    #[component(example = u64::default, default = u64::default))]
    id: u64,
    #[component(default = default_name)]
    name: String,
    age: Option<i32>,
}

fn default_name() -> String {
    "bob".to_string()
}

For enums and unnamed field structs you can define component at type level.

#[derive(Component)]
#[component(example = "Bus")]
enum VechileType {
    Rocket, Car, Bus, Submarine
}

Also you write complex enum combining all above types.

#[derive(Component)]
enum ErrorResponse {
    InvalidCredentials,
    #[component(default = String::default, example = "Pet not found")]
    NotFound(String),
    System {
        #[component(example = "Unknown system failure")]
        details: String,
    }
}

  1. json feature need to be enabled for json!(...) type to work. 

  2. Values are converted to string if json feature is not enabled.