Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions utoipa-gen/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

* Add support for expression for `title` and `names` (https://github.com/juhaku/utoipa/pull/1524)
* Add support for merging `OpenApi` derives with `merge(...)` (https://github.com/juhaku/utoipa/pull/1304)
* Add typed `examples(from = ...)` taking examples from a Rust expression implementing `IntoIterator` to `ToSchema`, `IntoParams`, `ToResponse`, `IntoResponses` and `request_body`, `responses` and `params` of `#[utoipa::path]`. Examples are converted to the type the schema, body or parameter describes, so an example of the wrong type fails to compile (https://github.com/juhaku/utoipa/pull/1639)
* Add named `examples(...)` to parameters of `IntoParams` and `#[utoipa::path]` (https://github.com/juhaku/utoipa/pull/1639)

### Changed

Expand All @@ -16,6 +18,7 @@
* Mark `Option` fields with `deserialize_with` or `with` and no `default` as required (https://github.com/juhaku/utoipa/pull/1627)
* chore: Pin uuid < 1.27 for MSRV 1.88 compatibility (https://github.com/juhaku/utoipa/pull/1630)
* Deny additional properties on struct variants of `deny_unknown_fields` enums (https://github.com/juhaku/utoipa/pull/1631)
* Place `examples` of `Vec` and other list types on the array schema instead of its `items`, and `examples` of map types on the object schema instead of its `propertyNames` and `additionalProperties`. This changes the generated output for anyone relying on the old placement (https://github.com/juhaku/utoipa/pull/1638)

## 6.0.1 - Sep 23 2026

Expand Down
6 changes: 5 additions & 1 deletion utoipa-gen/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,7 @@ impl ComponentSchema {
description_stream: Option<&ComponentDescription<'_>>,
) -> Result<(), Diagnostics> {
let example = features.pop_by(|feature| matches!(feature, Feature::Example(_)));
let examples = pop_feature!(features => Feature::Examples(_));
let additional_properties = pop_feature!(features => Feature::AdditionalProperties(_));
let nullable: Option<Nullable> =
pop_feature!(features => Feature::Nullable(_)).into_inner();
Expand Down Expand Up @@ -990,7 +991,8 @@ impl ComponentSchema {
@default
}?);

example.to_tokens(tokens)
example.to_tokens(tokens)?;
examples.to_tokens(tokens)
}

fn vec_to_tokens(
Expand All @@ -1002,6 +1004,7 @@ impl ComponentSchema {
description_stream: Option<&ComponentDescription<'_>>,
) -> Result<(), Diagnostics> {
let example = pop_feature!(features => Feature::Example(_));
let examples = pop_feature!(features => Feature::Examples(_));
let xml = features.extract_vec_xml_feature(type_tree)?;
let max_items = pop_feature!(features => Feature::MaxItems(_));
let min_items = pop_feature!(features => Feature::MinItems(_));
Expand Down Expand Up @@ -1095,6 +1098,7 @@ impl ComponentSchema {
default.to_tokens(tokens)?;
title.to_tokens(tokens)?;
example.to_tokens(tokens)?;
examples.to_tokens(tokens)?;
xml.to_tokens(tokens)?;

Ok(())
Expand Down
6 changes: 6 additions & 0 deletions utoipa-gen/src/component/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub trait Parse {
pub enum Feature {
Example(attributes::Example),
Examples(attributes::Examples),
ParamExamples(attributes::ParamExamples),
Default(attributes::Default),
Inline(attributes::Inline),
XmlAttr(attributes::XmlAttr),
Expand Down Expand Up @@ -176,6 +177,7 @@ impl ToTokensDiagnostics for Feature {
Feature::Default(default) => quote! { .default(#default) },
Feature::Example(example) => quote! { .example(Some(#example)) },
Feature::Examples(examples) => quote! { .examples(#examples) },
Feature::ParamExamples(examples) => examples.to_examples_from_iter()?.unwrap_or_default(),
Feature::XmlAttr(xml) => quote! { .xml(Some(#xml)) },
Feature::Format(format) => quote! { .format(Some(#format)) },
Feature::WriteOnly(write_only) => quote! { .write_only(#write_only) },
Expand Down Expand Up @@ -271,6 +273,7 @@ impl Display for Feature {
Feature::Default(default) => default.fmt(f),
Feature::Example(example) => example.fmt(f),
Feature::Examples(examples) => examples.fmt(f),
Feature::ParamExamples(examples) => examples.fmt(f),
Feature::XmlAttr(xml) => xml.fmt(f),
Feature::Format(format) => format.fmt(f),
Feature::WriteOnly(write_only) => write_only.fmt(f),
Expand Down Expand Up @@ -321,6 +324,7 @@ impl Validatable for Feature {
Feature::Default(default) => default.is_validatable(),
Feature::Example(example) => example.is_validatable(),
Feature::Examples(examples) => examples.is_validatable(),
Feature::ParamExamples(examples) => examples.is_validatable(),
Feature::XmlAttr(xml) => xml.is_validatable(),
Feature::Format(format) => format.is_validatable(),
Feature::WriteOnly(write_only) => write_only.is_validatable(),
Expand Down Expand Up @@ -385,6 +389,7 @@ is_validatable! {
attributes::Default,
attributes::Example,
attributes::Examples,
attributes::ParamExamples,
attributes::XmlAttr,
attributes::Format,
attributes::WriteOnly,
Expand Down Expand Up @@ -617,6 +622,7 @@ macro_rules! impl_feature_into_inner {
impl_feature_into_inner! {
attributes::Example,
attributes::Examples,
attributes::ParamExamples,
attributes::Default,
attributes::Inline,
attributes::XmlAttr,
Expand Down
74 changes: 68 additions & 6 deletions utoipa-gen/src/component/features/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::component::{schema, GenericType, TypeTree};
use crate::parse_utils::LitStrOrExpr;
use crate::path::parameter::{self, ParameterStyle};
use crate::schema_type::KnownFormat;
use crate::{parse_utils, AnyValue, Array, Diagnostics};
use crate::{parse_utils, AnyValue, Array, Diagnostics, ExamplesFrom};

use super::{impl_feature, Feature, Parse};
use quote::quote;
Expand Down Expand Up @@ -84,7 +84,22 @@ impl From<Example> for Feature {
impl_feature! {
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct Examples(Vec<AnyValue>);
pub enum Examples {
/// `examples(json!(...), "literal", function_path, ...)`
List(Vec<AnyValue>),
/// `examples(from = <expr>)` where items are converted to the type of the schema. Type
/// is `Self` unless set with [`Examples::set_type`].
From(Box<ExamplesFrom>, Option<Box<syn::Type>>),
}
}

impl Examples {
/// Set the type that `examples(from = ...)` items are converted to, unless already set.
pub fn set_type(&mut self, ty: &syn::Type) {
if let Self::From(_, example_type @ None) = self {
*example_type = Some(Box::new(ty.clone()));
}
}
}

impl Parse for Examples {
Expand All @@ -95,7 +110,11 @@ impl Parse for Examples {
let examples;
syn::parenthesized!(examples in input);

Ok(Self(
if ExamplesFrom::peek(&examples) {
return ExamplesFrom::parse(&examples).map(|from| Self::From(Box::new(from), None));
}

Ok(Self::List(
Punctuated::<AnyValue, Token![,]>::parse_terminated_with(
&examples,
AnyValue::parse_any,
Expand All @@ -108,9 +127,13 @@ impl Parse for Examples {

impl ToTokens for Examples {
fn to_tokens(&self, tokens: &mut TokenStream) {
if !self.0.is_empty() {
let examples = Array::Borrowed(&self.0).to_token_stream();
examples.to_tokens(tokens);
match self {
Self::List(examples) if !examples.is_empty() => {
Array::Borrowed(examples).to_tokens(tokens);
}
Self::List(_) => (),
Self::From(from, Some(ty)) => from.to_values(&ty.to_token_stream()).to_tokens(tokens),
Self::From(from, None) => from.to_values(&quote!(Self)).to_tokens(tokens),
}
}
}
Expand All @@ -121,6 +144,40 @@ impl From<Examples> for Feature {
}
}

impl_feature! {"examples" =>
/// Named examples of a parameter, `examples(("name" = (...)), ...)` or
/// `examples(from = <expr>)` where each item is a `(name, value)` tuple.
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct ParamExamples(Box<crate::path::example::Examples>, Option<Box<syn::Type>>);
}

impl ParamExamples {
/// Set the type that `examples(from = ...)` values are converted to, unless already set.
pub fn set_type(&mut self, ty: &syn::Type) {
if self.1.is_none() {
self.1 = Some(Box::new(ty.clone()));
}
}

/// Get `.examples_from_iter(...)` builder call, if any examples are defined.
pub fn to_examples_from_iter(&self) -> Result<Option<TokenStream>, Diagnostics> {
self.0.to_examples_from_iter(self.1.as_deref())
}
}

impl Parse for ParamExamples {
fn parse(input: ParseStream, _: Ident) -> syn::Result<Self> {
input.parse().map(|examples| Self(Box::new(examples), None))
}
}

impl From<ParamExamples> for Feature {
fn from(value: ParamExamples) -> Self {
Feature::ParamExamples(value)
}
}

impl_feature! {"xml" =>
#[derive(Default, Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
Expand Down Expand Up @@ -500,6 +557,11 @@ impl ValueType {
pub fn as_type_tree(&self) -> Result<TypeTree<'_>, Diagnostics> {
TypeTree::from_type(&self.0)
}

/// Get the [`syn::Type`] of the value type.
pub fn ty(&self) -> &syn::Type {
&self.0
}
}

impl Parse for ValueType {
Expand Down
19 changes: 17 additions & 2 deletions utoipa-gen/src/component/into_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use crate::{
self,
attributes::{
AdditionalProperties, AllowReserved, Example, Explode, Format, Ignore, Inline,
IntoParamsNames, Nullable, ReadOnly, Rename, RenameAll, SchemaWith, Style,
WriteOnly, XmlAttr,
IntoParamsNames, Nullable, ParamExamples, ReadOnly, Rename, RenameAll, SchemaWith,
Style, WriteOnly, XmlAttr,
},
validation::{
ExclusiveMaximum, ExclusiveMinimum, MaxItems, MaxLength, Maximum, MinItems,
Expand Down Expand Up @@ -299,6 +299,7 @@ impl Parse for FieldFeatures {
Style,
AllowReserved,
Example,
ParamExamples,
Explode,
SchemaWith,
component::features::attributes::Required,
Expand Down Expand Up @@ -423,6 +424,20 @@ impl Param {
.as_ref()
.map_try(|value_type| value_type.as_type_tree())?
.unwrap_or(type_tree);

// typed examples are checked against the value type unless it is a virtual `Object`
// or `Value` type, in which case the actual field type is used
let examples_type = match &value_type {
Some(value_type) if !(component.is_object() || component.is_value()) => {
value_type.ty()
}
_ => &field.ty,
};
for feature in &mut param_features {
if let Feature::ParamExamples(examples) = feature {
examples.set_type(examples_type);
}
}
let alias_type = component.get_alias_type()?;
let alias_type_tree = alias_type.as_ref().map_try(TypeTree::from_type)?;
let component = alias_type_tree.as_ref().unwrap_or(&component);
Expand Down
17 changes: 17 additions & 0 deletions utoipa-gen/src/component/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,23 @@ impl NamedStructSchema {
let override_type_tree = value_type
.as_ref()
.map_try(|value_type| value_type.as_type_tree())?;

// typed examples are checked against the value type unless it is a virtual `Object` or
// `Value` type, in which case the actual field type is used
let examples_type = match (&value_type, &override_type_tree) {
(Some(value_type), Some(type_tree))
if !(type_tree.is_object() || type_tree.is_value()) =>
{
value_type.ty()
}
_ => &field.ty,
};
for feature in &mut field_features {
if let Feature::Examples(examples) = feature {
examples.set_type(examples_type);
}
}

let comments = CommentAttributes::from_attributes(&field.attrs);
let description = &ComponentDescription::CommentAttributes(&comments);

Expand Down
Loading