utoipa

Derive Macro IntoParams

source
#[derive(IntoParams)]
{
    // Attributes available to this derive:
    #[param]
    #[into_params]
}
Expand description

Generate path parameters from struct’s fields.

This is #[derive] implementation for IntoParams trait.

Typically path parameters need to be defined within #[utoipa::path(...params(...))] section for the endpoint. But this trait eliminates the need for that when structs are used to define parameters. Still [std::primitive] and String path parameters or tuple style path parameters need to be defined within params(...) section if description or other than default configuration need to be given.

You can use the Rust’s own #[deprecated] attribute on field to mark it as deprecated and it will reflect to the generated OpenAPI spec.

#[deprecated] attribute supports adding additional details such as a reason and or since version but this is is not supported in OpenAPI. OpenAPI has only a boolean flag to determine deprecation. While it is totally okay to declare deprecated with reason #[deprecated = "There is better way to do this"] the reason would not render in OpenAPI spec.

Doc comment on struct fields will be used as description for the generated parameters.

#[derive(utoipa::IntoParams)]
struct Query {
    /// Query todo items by name.
    name: String
}

§IntoParams Container Attributes for #[into_params(...)]

The following attributes are available for use in on the container attribute #[into_params(...)] for the struct deriving IntoParams:

  • names(...) Define comma separated list of names for unnamed fields of struct used as a path parameter. Only supported on unnamed structs.
  • style = ... Defines how all parameters are serialized by ParameterStyle. Default values are based on parameter_in attribute.
  • parameter_in = ... = Defines where the parameters of this field are used with a value from openapi::path::ParameterIn. There is no default value, if this attribute is not supplied, then the value is determined by the parameter_in_provider in IntoParams::into_params().
  • rename_all = ... Can be provided to alternatively to the serde’s rename_all attribute. Effectively provides same functionality.

Use names to define name for single unnamed argument.

#[derive(IntoParams)]
#[into_params(names("id"))]
struct Id(u64);

Use names to define names for multiple unnamed arguments.

#[derive(IntoParams)]
#[into_params(names("id", "name"))]
struct IdAndName(u64, String);

§IntoParams Field Attributes for #[param(...)]

The following attributes are available for use in the #[param(...)] on struct fields:

  • style = ... Defines how the parameter is serialized by ParameterStyle. Default values are based on parameter_in attribute.

  • explode Defines whether new parameter=value pair is created for each parameter within object or array.

  • allow_reserved Defines whether reserved characters :/?#[]@!$&'()*+,;= is allowed within value.

  • example = ... Can be method reference or json!(...). Given example will override any example in underlying parameter type.

  • value_type = ... Can be used to override default type derived from type of the field used in OpenAPI spec. This is useful in cases where the default type does not correspond to the actual type e.g. when any third-party types are used which are not ToSchemas nor primitive types. The value can be any Rust type what normally could be used to serialize to JSON, or either virtual type Object or Value, or an alias defined using #[aliases(..)]. Object will be rendered as generic OpenAPI object (type: object). Value will be rendered as any OpenAPI value (i.e. no type restriction).

  • inline If set, the schema for this field’s type needs to be a ToSchema, and the schema definition will be inlined.

  • default = ... Can be method reference or json!(...).

  • format = ... May either be variant of the KnownFormat enum, or otherwise an open value as a string. 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

  • xml(...) Can be used to define Xml object properties applicable to named fields. See configuration options at xml attributes of ToSchema

  • nullable Defines property is nullable (note this is different to non-required).

  • required = ... Can be used to enforce required status for the parameter. See rules

  • rename = ... Can be provided to alternatively to the serde’s rename attribute. Effectively provides same functionality.

  • multiple_of = ... Can be used to define multiplier for a value. Value is considered valid division will result an integer. Value must be strictly above 0.

  • maximum = ... Can be used to define inclusive upper bound to a number value.

  • minimum = ... Can be used to define inclusive lower bound to a number value.

  • exclusive_maximum = ... Can be used to define exclusive upper bound to a number value.

  • exclusive_minimum = ... Can be used to define exclusive lower bound to a number value.

  • max_length = ... Can be used to define maximum length for string types.

  • min_length = ... Can be used to define minimum length for string types.

  • pattern = ... Can be used to define valid regular expression in ECMA-262 dialect the field value must match.

  • max_items = ... Can be used to define maximum items allowed for array fields. Value must be non-negative integer.

  • min_items = ... Can be used to define minimum items allowed for array fields. Value must be non-negative integer.

  • schema_with = ... Use schema created by provided function reference instead of the default derived schema. The function must match to fn() -> Into<RefOr<Schema>>. It does not accept arguments and must return anything that can be converted into RefOr<Schema>.

  • additional_properties = ... Can be used to define free form types for maps such as HashMap and BTreeMap. Free form type enables use of arbitrary types within map values. Supports formats additional_properties and additional_properties = true.

§Field nullability and required rules

Same rules for nullability and required status apply for IntoParams field attributes as for ToSchema field attributes. See the rules.

§Partial #[serde(...)] attributes support

IntoParams derive has partial support for serde attributes. These supported attributes will reflect to the generated OpenAPI doc. The following attributes are currently supported:

  • rename_all = "..." Supported at the container level.
  • rename = "..." Supported only at the field level.
  • default Supported at the container level and field level according to serde attributes.
  • skip_serializing_if = "..." Supported only at the field level.
  • with = ... Supported only at field level.
  • skip_serializing = "..." Supported only at the field or variant level.
  • skip_deserializing = "..." Supported only at the field or variant level.
  • skip = "..." Supported only at the field level.

Other serde attributes will impact the serialization but will not be reflected on the generated OpenAPI doc.

§Examples

Demonstrate IntoParams usage with resolving Path and Query parameters with actix-web.

use actix_web::{get, HttpResponse, Responder};
use actix_web::web::{Path, Query};
use serde::Deserialize;
use serde_json::json;
use utoipa::IntoParams;

#[derive(Deserialize, IntoParams)]
struct PetPathArgs {
    /// Id of pet
    id: i64,
    /// Name of pet
    name: String,
}

#[derive(Deserialize, IntoParams)]
struct Filter {
    /// Age filter for pets
    #[deprecated]
    #[param(style = Form, explode, allow_reserved, example = json!([10]))]
    age: Option<Vec<i32>>,
}

#[utoipa::path(
    params(PetPathArgs, Filter),
    responses(
        (status = 200, description = "success response")
    )
)]
#[get("/pet/{id}/{name}")]
async fn get_pet(pet: Path<PetPathArgs>, query: Query<Filter>) -> impl Responder {
    HttpResponse::Ok().json(json!({ "id": pet.id }))
}

Demonstrate IntoParams usage with the #[into_params(...)] container attribute to be used as a path query, and inlining a schema query field:

use serde::Deserialize;
use utoipa::{IntoParams, ToSchema};

#[derive(Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
enum PetKind {
    Dog,
    Cat,
}

#[derive(Deserialize, IntoParams)]
#[into_params(style = Form, parameter_in = Query)]
struct PetQuery {
    /// Name of pet
    name: Option<String>,
    /// Age of pet
    age: Option<i32>,
    /// Kind of pet
    #[param(inline)]
    kind: PetKind
}

#[utoipa::path(
    get,
    path = "/get_pet",
    params(PetQuery),
    responses(
        (status = 200, description = "success response")
    )
)]
async fn get_pet(query: PetQuery) {
    // ...
}

Override String with i64 using value_type attribute.

#[derive(IntoParams)]
#[into_params(parameter_in = Query)]
struct Filter {
    #[param(value_type = i64)]
    id: String,
}

Override String with Object using value_type attribute. Object will render as type: object in OpenAPI spec.

#[derive(IntoParams)]
#[into_params(parameter_in = Query)]
struct Filter {
    #[param(value_type = Object)]
    id: String,
}

You can use a generic type to override the default type of the field.

#[derive(IntoParams)]
#[into_params(parameter_in = Query)]
struct Filter {
    #[param(value_type = Option<String>)]
    id: String
}

You can even override a [Vec] with another one.

#[derive(IntoParams)]
#[into_params(parameter_in = Query)]
struct Filter {
    #[param(value_type = Vec<i32>)]
    id: Vec<String>
}

We can override value with another ToSchema.

#[derive(ToSchema)]
struct Id {
    value: i64,
}

#[derive(IntoParams)]
#[into_params(parameter_in = Query)]
struct Filter {
    #[param(value_type = Id)]
    id: String
}

Example with validation attributes.

#[derive(utoipa::IntoParams)]
struct Item {
    #[param(maximum = 10, minimum = 5, multiple_of = 2.5)]
    id: i32,
    #[param(max_length = 10, min_length = 5, pattern = "[a-z]*")]
    value: String,
    #[param(max_items = 5, min_items = 1)]
    items: Vec<String>,
}

Use schema_with to manually implement schema for a field.

fn custom_type() -> Object {
    ObjectBuilder::new()
        .schema_type(utoipa::openapi::SchemaType::String)
        .format(Some(utoipa::openapi::SchemaFormat::Custom(
            "email".to_string(),
        )))
        .description(Some("this is the description"))
        .build()
}

#[derive(utoipa::IntoParams)]
#[into_params(parameter_in = Query)]
struct Query {
    #[param(schema_with = custom_type)]
    email: String,
}