#[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 struct
s 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 byParameterStyle
. Default values are based onparameter_in
attribute.parameter_in = ...
= Defines where the parameters of this field are used with a value fromopenapi::path::ParameterIn
. There is no default value, if this attribute is not supplied, then the value is determined by theparameter_in_provider
inIntoParams::into_params()
.rename_all = ...
Can be provided to alternatively to the serde’srename_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 byParameterStyle
. Default values are based onparameter_in
attribute. -
explode
Defines whether newparameter=value
pair is created for each parameter withinobject
orarray
. -
allow_reserved
Defines whether reserved characters:/?#[]@!$&'()*+,;=
is allowed within value. -
example = ...
Can be method reference orjson!(...)
. 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 notToSchema
s norprimitive
types. The value can be any Rust type what normally could be used to serialize to JSON, or either virtual typeObject
orValue
, 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. notype
restriction). -
inline
If set, the schema for this field’s type needs to be aToSchema
, and the schema definition will be inlined. -
default = ...
Can be method reference orjson!(...)
. -
format = ...
May either be variant of theKnownFormat
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 defineXml
object properties applicable to named fields. See configuration options at xml attributes ofToSchema
-
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’srename
attribute. Effectively provides same functionality. -
multiple_of = ...
Can be used to define multiplier for a value. Value is considered valid division will result aninteger
. Value must be strictly above0
. -
maximum = ...
Can be used to define inclusive upper bound to anumber
value. -
minimum = ...
Can be used to define inclusive lower bound to anumber
value. -
exclusive_maximum = ...
Can be used to define exclusive upper bound to anumber
value. -
exclusive_minimum = ...
Can be used to define exclusive lower bound to anumber
value. -
max_length = ...
Can be used to define maximum length forstring
types. -
min_length = ...
Can be used to define minimum length forstring
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 forarray
fields. Value must be non-negative integer. -
min_items = ...
Can be used to define minimum items allowed forarray
fields. Value must be non-negative integer. -
schema_with = ...
Useschema
created by provided function reference instead of the default derivedschema
. The function must match tofn() -> Into<RefOr<Schema>>
. It does not accept arguments and must return anything that can be converted intoRefOr<Schema>
. -
additional_properties = ...
Can be used to define free form types for maps such asHashMap
andBTreeMap
. Free form type enables use of arbitrary types within map values. Supports formatsadditional_properties
andadditional_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,
}