Trait utoipa::ToSchema

source ·
pub trait ToSchema<'__s> {
    // Required method
    fn schema() -> (&'__s str, RefOr<Schema>);

    // Provided method
    fn aliases() -> Vec<(&'__s str, Schema)> { ... }
}
Expand description

Trait for implementing OpenAPI Schema object.

Generated schemas can be referenced or reused in path operations.

This trait is derivable and can be used with [#derive] attribute. For a details of #[derive(ToSchema)] refer to derive documentation.

§Examples

Use #[derive] to implement ToSchema trait.

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

Following manual implementation is equal to above derive one.

impl<'__s> utoipa::ToSchema<'__s> for Pet {
    fn schema() -> (&'__s str, utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>) {
         (
            "Pet",
            utoipa::openapi::ObjectBuilder::new()
                .property(
                    "id",
                    utoipa::openapi::ObjectBuilder::new()
                        .schema_type(utoipa::openapi::SchemaType::Integer)
                        .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
                            utoipa::openapi::KnownFormat::Int64,
                        ))),
                )
                .required("id")
                .property(
                    "name",
                    utoipa::openapi::ObjectBuilder::new()
                        .schema_type(utoipa::openapi::SchemaType::String),
                )
                .required("name")
                .property(
                    "age",
                    utoipa::openapi::ObjectBuilder::new()
                        .schema_type(utoipa::openapi::SchemaType::Integer)
                        .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
                            utoipa::openapi::KnownFormat::Int32,
                        ))),
                )
                .example(Some(serde_json::json!({
                  "name":"bob the cat","id":1
                })))
                .into(),
        ) }
}

Required Methods§

source

fn schema() -> (&'__s str, RefOr<Schema>)

Return a tuple of name and schema or reference to a schema that can be referenced by the name or inlined directly to responses, request bodies or parameters.

Provided Methods§

source

fn aliases() -> Vec<(&'__s str, Schema)>

Optional set of alias schemas for the ToSchema::schema.

Typically there is no need to manually implement this method but it is instead implemented by derive ToSchema when #[aliases(...)] attribute is defined.

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<'__s> ToSchema<'__s> for TupleUnit