Skip to content

Add typed examples with examples(from = ...) and parameter examples - #1639

Open
wuerges wants to merge 12 commits into
juhaku:masterfrom
wuerges:typed-examples-from
Open

wuerges wants to merge 12 commits into
juhaku:masterfrom
wuerges:typed-examples-from

Conversation

@wuerges

@wuerges wuerges commented Oct 13, 2026

Copy link
Copy Markdown

Stacked on #1638 (list and map examples placement), whose 5 commits are also included here. Please review that PR first; the commits for this PR start at "feat: add examples to Parameter".

Today every example is parsed by AnyValue::parse_any, which accepts a literal, json!(...) or a function path. None of these forms check that an example matches the type it documents, and no form gives several examples from one Rust expression: examples(f) with f returning a Vec produces one example that is an array. This PR adds one form that is checked against the type and accepted everywhere utoipa takes examples. All existing forms behave exactly as before.

Related: #199 ("Check json examples for types that implement Serialize").

Schemas (ToSchema)

#[derive(ToSchema, Serialize)]
#[schema(examples(from = [Zone::A, Zone::B]))]
enum Zone { A, B }

#[derive(ToSchema, Serialize)]
#[schema(examples(from = Nameservers::examples()))]
struct Nameservers(Vec<String>);

#[derive(ToSchema, Serialize)]
struct Record {
    #[schema(examples(from = ["example.com.", "example.org."]))]
    name: String,
    #[schema(value_type = String, examples(from = ["2026-01-01"]))]
    published: Date,
}

<expr> is any IntoIterator. Each item becomes one entry of examples, in order. Each item is converted with Into::into to:

  • Self on a struct, an enum or an enum variant;
  • the field type on a field, or value_type when it is given. For the virtual value_type = Object / Value, the real field type is used.

The item is then serialised with serde_json::to_value. An example of the wrong type fails to compile, and the error points at the attribute:

error[E0277]: the trait bound `std::string::String: From<{integer}>` is not satisfied
 --> src/lib.rs:6:30
  |
6 |     #[schema(examples(from = [42]))]
  |                              ^^^^ the trait `From<{integer}>` is not implemented for `std::string::String`

I chose Into<T> over requiring exactly T so that &str items work for String fields and Vec items work for Option<Vec<_>> fields. The cost is that integer literals do not infer the target type (for a u64, write 1u64). This is documented.

Request body, responses, ToResponse, IntoResponses

Media type examples is a name → Example map, so here each item is a (name, value) tuple, where name: Into<String> and value: Into<Body>:

#[utoipa::path(
    post,
    path = "/pets",
    request_body(content = Pet, examples(from = [("Rex", Pet::new("Rex"))])),
    responses(
        (status = 200, body = [Pet], examples(from = [("pets", vec![Pet::new("Rex")])]))
    )
)]

The body type comes from content = … / body = … ([T] takes Vec<T> items). For ToResponse and IntoResponses, it is the derived type. When there is no explicit body type, the macro gives a compile error that asks for one. Names are required rather than generated automatically: this is explicit, it matches the existing named form, and it avoids ambiguity when the body type is itself a tuple.

Parameters

OpenAPI 3.1 Parameter Objects have an examples map, but utoipa::openapi::path::Parameter only had example. This PR adds:

  • Parameter::examples: BTreeMap<String, RefOr<Example>> and ParameterBuilder::examples_from_iter in utoipa. Parameter is #[non_exhaustive], so this is not a breaking change.
  • examples(...) on #[param(...)] (IntoParams) and on params((...)) tuples in #[utoipa::path]. It accepts both the existing named form ("name" = (value = json!(..))) and from = [(name, value)], with values converted to the field or parameter type (or value_type).

Implementation

  • ExamplesFrom (in utoipa-gen/src/lib.rs, next to AnyValue) is the single parser for from = <expr>. It generates both the value form and the named form, using quote_spanned! at the expression's span.
  • attributes::Examples is now an enum with two variants: the existing list, or from plus the target type. Field and IntoParams code fills in the type; containers default to Self.
  • path::example::Examples (the list of named Examples, or from) replaces Punctuated<Example, Comma> in MediaTypeAttr, in response derives, and in the new ParamExamples feature.
  • There is no new public runtime API apart from Parameter::examples. The generated code uses only core/std, utoipa::gen::serde_json and ExampleBuilder.
  • If serialisation fails, the generated code panics with failed to serialize example from examples(from = ...), and the panic location is the attribute. PartialSchema::schema() is infallible, and today's json!(f()) also unwraps inside serde_json.

Tests

  • schema_derive_test.rs: a unit enum container, a newtype over Vec (examples go on the array), fields covering &str→String, Vec, Option<Vec<_>>, HashMap and value_type, mixed enum variants, and a generic struct using Self.
  • request_body_derive_test.rs: content = Foo, plus content groups with [Foo] and inline(Foo).
  • path_response_derive_test.rs, response_derive_test.rs: a response body, ToResponse and IntoResponses.
  • path_derive.rs: IntoParams fields (from and the named form) and params tuples.
  • utoipa unit test for ParameterBuilder::examples_from_iter.
  • compile_fail doctests (the repo does not use trybuild): a wrong item type on a field, a wrong item type on an enum, and from without a body type.

Not included

  • A singular typed example = from(...). The singular example is deprecated in favour of examples.
  • Parameters whose type is inferred from the handler signature (actix/axum/rocket) and not written in params(...) cannot use from yet. They get a compile error asking for an explicit type.

🤖 Generated with Claude Code

@wuerges
wuerges force-pushed the typed-examples-from branch from 4e0bd55 to d6deb14 Compare October 13, 2026 18:23
@wuerges

wuerges commented Oct 14, 2026

Copy link
Copy Markdown
Author

The CI failures here don't come from this PR. They're caused by a dependency release:

error: rustc 1.88.0 is not supported by the following package:
  actix-server@2.10.0 requires rustc 1.89

Cargo.lock is gitignored, so CI resolves the latest versions on each run, and actix-server 2.10.0 raised its MSRV to 1.89 while CI and rust-toolchain.toml are on 1.88. This breaks test (utoipa-gen) and test (examples). test (utoipa) was cancelled because of them; all of its steps that ran had passed.

Locally, with actix-server pinned to 2.9.0 and actix-rt to 2.10.0 (2.9.0 doesn't build against actix-rt 2.15), just test utoipa-gen utoipa passes on this branch.

Two ways to fix CI: bump the toolchain and rust-version to 1.89, or pin those two crates in CI. I'm happy to open a separate PR for whichever you prefer.

wuerges and others added 12 commits October 30, 2026 19:46
Examples given with #[schema(examples(...))] on a Vec or other
list-like type should describe the whole list and be placed on the
array schema, not on its items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
vec_to_tokens took the deprecated singular `example` off the features
for the array itself, but left `examples` in the features passed to
the item schema. As a result #[schema(examples(...))] on a Vec,
LinkedList, set, SmallVec, slice or array ended up on `items`.

Pop Feature::Examples together with the other array-level features and
emit it on the ArrayBuilder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
map_to_tokens popped the singular `example` but passed `examples` on
to both the propertyNames and additionalProperties child schemas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OpenAPI 3.1 Parameter Object has an `examples` map of named Example
objects next to the single `example`. Add Parameter::examples and
ParameterBuilder::examples_from_iter mirroring Content.

Parameter is #[non_exhaustive], so the new field is not a breaking
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cover container, field, variant, newtype and generic schemas, request
body and response content, ToResponse/IntoResponses derives, and
IntoParams / path tuple parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add `examples(from = <expr>)` to #[schema(...)] where <expr> is any
IntoIterator. Each item is converted with Into::into to the type the
examples describe and serialized with serde_json, so an example of the
wrong type fails to compile at the attribute.

The type is `Self` for container and variant examples, and the field
type, or `value_type` when given, for field examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…content

Media type `examples` is a map of named examples, so for
request_body, responses and the ToResponse / IntoResponses derives each
item of `examples(from = <expr>)` is a `(name, value)` tuple where name
is Into<String> and value is converted with Into::into to the body type.
A `[T]` body takes Vec<T> examples. Content without an explicit body
type gives a compile error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OpenAPI 3.1 parameters have an `examples` map of named examples. Accept
`examples(...)` on #[param(...)], IntoParams fields and params tuples in
#[utoipa::path] in the same forms as request and response content:
`examples(("name" = (value = json!(...))), ...)` and
`examples(from = <expr>)` where each item is a `(name, value)` tuple and
value is converted with Into::into to the parameter type, or its
`value_type` when given.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a "Typed examples" section to the ToSchema docs and document the
`from = ...` form for request and response content, ToResponse,
IntoResponses, IntoParams and path parameters. Add compile_fail
doctests for examples of the wrong type and for typed examples without
a body type. Also complete two truncated `examples(...)` bullets in
the enum docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@wuerges
wuerges force-pushed the typed-examples-from branch from d6deb14 to f474796 Compare October 30, 2026 22:48
@wuerges

wuerges commented Oct 30, 2026

Copy link
Copy Markdown
Author

Rebased onto current master (c7fd8ad, which includes the zip 9.0 bump and the swagger-ui release version update). There were no conflicts and the code is unchanged. This PR still builds on #1638, so its first commits are the ones from that PR. The earlier CI failure on this PR came from the old rustc 1.88 toolchain not supporting actix-server 2.10, which master has since fixed. The new CI workflow is waiting for maintainer approval to run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant