diff --git a/.github/actions/publish/publish.sh b/.github/actions/publish/publish.sh index ab9d7b413..59bc69e75 100755 --- a/.github/actions/publish/publish.sh +++ b/.github/actions/publish/publish.sh @@ -42,7 +42,7 @@ fi echo "$token" | cargo login while read -r module; do # crate=$(echo "$ref" | sed 's|-[0-9]*\.[0-9]*\.[0-9].*||') - crate=${ref/-[0-9]\.[0-9]\.[0-9]*/} + crate=${ref/-[0-9]*\.[0-9]*\.[0-9]*/} if [[ "$crate" != "$module" ]]; then echo "Module: $module does not match to release crate: $crate, skipping release for module" continue diff --git a/Cargo.toml b/Cargo.toml index 5708cf5f7..804071101 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,20 @@ members = [ "utoipa-actix-web", ] +# cookie 0.18.1 (via rocket_http) does not compile against time 0.3.52+ +# (Parsable::parse gained a defaults argument). Cap until cookie releases a fix. +# Keeps `just test` / fresh resolves working without committing Cargo.lock. +[workspace.dependencies] +time = { version = ">=0.3, <0.3.52" } + +[workspace.lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } + +[workspace.lints.clippy] +# Enforced to guard against regressions of large stack allocations in generated +# code (see https://github.com/juhaku/utoipa/issues/1454). +large_stack_arrays = "deny" + # Crates published to crates.io under the meteroid-oss fork, in dependency order. # The core three (`-config`, `-gen`, `meteroid-utoipa`) carry the fork's custom # features (e.g. `tagged_discriminator`); `-axum` and `-scalar` are the framework diff --git a/README.md b/README.md index 4bec19ca5..d55f369a7 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ Add dependency declaration to `Cargo.toml`. ```toml [dependencies] -utoipa = "5" +utoipa = "6" ``` ## Examples diff --git a/RELEASING.md b/RELEASING.md index f405dd87c..2349fe9e8 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -4,11 +4,11 @@ This fork publishes five crates to crates.io, in dependency order: | crates.io name | path | import as (unchanged) | version | | ------------------------ | ---------------- | --------------------- | ------- | -| `meteroid-utoipa-config` | `utoipa-config/` | `utoipa_config` | 0.1.2 | -| `meteroid-utoipa-gen` | `utoipa-gen/` | `utoipa_gen` | 5.6.0 | -| `meteroid-utoipa` | `utoipa/` | `utoipa` | 5.6.0 | -| `meteroid-utoipa-axum` | `utoipa-axum/` | `utoipa_axum` | 0.2.0 | -| `meteroid-utoipa-scalar` | `utoipa-scalar/` | `utoipa_scalar` | 0.3.0 | +| `meteroid-utoipa-config` | `utoipa-config/` | `utoipa_config` | 0.1.3 | +| `meteroid-utoipa-gen` | `utoipa-gen/` | `utoipa_gen` | 6.0.0 | +| `meteroid-utoipa` | `utoipa/` | `utoipa` | 6.0.0 | +| `meteroid-utoipa-axum` | `utoipa-axum/` | `utoipa_axum` | 0.3.0 | +| `meteroid-utoipa-scalar` | `utoipa-scalar/` | `utoipa_scalar` | 0.4.0 | The crates.io **package** names are prefixed with `meteroid-`, but the **library** names are kept (`utoipa`, `utoipa_gen`, `utoipa_config`, `utoipa_axum`, @@ -16,7 +16,7 @@ names are kept (`utoipa`, `utoipa_gen`, `utoipa_config`, `utoipa_axum`, ```toml [dependencies] -meteroid-utoipa = "5" +meteroid-utoipa = "6" ``` ```rust @@ -67,9 +67,9 @@ you probably forgot to bump the `Cargo.toml` version(s). The crates have different versions, but you only pick **one** tag, and it's just a trigger — it does not decide what gets published (that comes from each -crate's `Cargo.toml`). Use the **`meteroid-utoipa` version**, e.g. `v5.6.0`. That +crate's `Cargo.toml`). Use the **`meteroid-utoipa` version**, e.g. `v6.0.0`. That is the crate you and downstream depend on, so the release *is* "meteroid-utoipa -5.6.0". The others ride along automatically: +6.0.0". The others ride along automatically: - `meteroid-utoipa-gen` moves **in lockstep** with `meteroid-utoipa` (same number — the derive-macro crate and its runtime are a matched pair), so it is covered. @@ -87,11 +87,11 @@ are independent of upstream `utoipa` — there is no collision on crates.io. Bum only the crates that carry a change of the fork's own (versus upstream juhaku/utoipa): -- `meteroid-utoipa-gen` and `meteroid-utoipa` currently diverge from upstream 5.5.0 - by two opt-in, backward-compatible features (`tagged_discriminator` and flatten - support in `IntoParams`), hence the minor bump to **5.6.0**. -- `meteroid-utoipa-config` is unchanged from upstream, so it stays at **0.1.2**. -- `meteroid-utoipa-axum` (**0.2.0**) and `meteroid-utoipa-scalar` (**0.3.0**) are +- `meteroid-utoipa-gen` and `meteroid-utoipa` track upstream 6.0.0 plus two opt-in, + backward-compatible features (`tagged_discriminator` and flatten support in + `IntoParams`), and are published as **6.0.0**. +- `meteroid-utoipa-config` is unchanged from upstream, so it matches it at **0.1.3**. +- `meteroid-utoipa-axum` (**0.3.0**) and `meteroid-utoipa-scalar` (**0.4.0**) are the framework bindings, unchanged from upstream; they only depend on the renamed core. Bump them when their own `Cargo.toml` changes. diff --git a/examples/actix-web-multipart/Cargo.toml b/examples/actix-web-multipart/Cargo.toml index 73cf57fda..01c7f90bb 100644 --- a/examples/actix-web-multipart/Cargo.toml +++ b/examples/actix-web-multipart/Cargo.toml @@ -4,6 +4,8 @@ version = "0.1.0" edition = "2021" [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" actix-multipart = "0.7" utoipa = { path = "../../utoipa", features = ["actix_extras"] } diff --git a/examples/actix-web-multiple-api-docs-with-scopes/Cargo.toml b/examples/actix-web-multiple-api-docs-with-scopes/Cargo.toml index 1984b3d54..5d4e80d81 100644 --- a/examples/actix-web-multiple-api-docs-with-scopes/Cargo.toml +++ b/examples/actix-web-multiple-api-docs-with-scopes/Cargo.toml @@ -11,6 +11,8 @@ authors = [ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" serde = { version = "1.0", features = ["derive"] } env_logger = "0.11.0" diff --git a/examples/actix-web-scopes-binding/Cargo.toml b/examples/actix-web-scopes-binding/Cargo.toml index 4e417f820..ba2f8386d 100644 --- a/examples/actix-web-scopes-binding/Cargo.toml +++ b/examples/actix-web-scopes-binding/Cargo.toml @@ -5,6 +5,8 @@ version = "0.1.0" edition = "2021" [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" serde = { version = "1.0", features = ["derive"] } env_logger = "0.11.0" diff --git a/examples/generics-actix/Cargo.toml b/examples/generics-actix/Cargo.toml index 58c3e186d..eb3ab245e 100644 --- a/examples/generics-actix/Cargo.toml +++ b/examples/generics-actix/Cargo.toml @@ -11,6 +11,8 @@ authors = [ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" env_logger = "0.10.0" geo-types = { version = "0.7", features = ["serde"] } diff --git a/examples/openapi-3_2-sse/Cargo.toml b/examples/openapi-3_2-sse/Cargo.toml new file mode 100644 index 000000000..df192dd43 --- /dev/null +++ b/examples/openapi-3_2-sse/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "openapi-3_2-sse" +description = "Axum example documenting a Server-Sent Events (SSE) endpoint using OpenAPI 3.2" +version = "0.1.0" +edition = "2021" +license = "MIT" +authors = ["Drifter-J "] + +[dependencies] +axum = "0.8.0" +futures-util = "0.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1.17", features = ["full"] } +tokio-stream = "0.1" +utoipa = { path = "../../utoipa", features = ["axum_extras", "uuid"] } +utoipa-axum = { path = "../../utoipa-axum" } +utoipa-swagger-ui = { path = "../../utoipa-swagger-ui", features = ["axum"] } +uuid = { version = "1", features = ["serde", "v4"] } +rand = "0.8" + +[workspace] diff --git a/examples/openapi-3_2-sse/README.md b/examples/openapi-3_2-sse/README.md new file mode 100644 index 000000000..17c4f984c --- /dev/null +++ b/examples/openapi-3_2-sse/README.md @@ -0,0 +1,15 @@ +# openapi-3_2-sse + +This example demonstrates documenting a Server-Sent Events endpoint using `utoipa`'s +OpenAPI 3.2 support: opting in to `openapi: "3.2.0"` output and describing the +`text/event-stream` response with the new `itemSchema` media type keyword. + +Run with: +```bash +cargo run +``` + +Then either: + +- Browse to `http://localhost:8080/swagger-ui/` to inspect the generated OpenAPI 3.2 document, or +- Stream events directly with `curl -N http://localhost:8080/pets/events` diff --git a/examples/openapi-3_2-sse/src/main.rs b/examples/openapi-3_2-sse/src/main.rs new file mode 100644 index 000000000..1546d3e70 --- /dev/null +++ b/examples/openapi-3_2-sse/src/main.rs @@ -0,0 +1,124 @@ +//! Server-Sent Events (SSE) example documented with OpenAPI 3.2. +//! +//! OpenAPI 3.2 adds support for streaming/sequential media types such as `text/event-stream`, +//! `application/jsonl` and `application/json-seq`. +//! Refer to [Announcing OpenAPI v3.2](https://www.openapis.org/blog/2025/09/23/announcing-openapi-v3-2) +//! +//! This example shows how to: +//! +//! - opt in to `utoipa`'s OpenAPI 3.2 output via the `#[openapi(version = "3.2.0")]` derive attribute +//! - describe a `text/event-stream` SSE endpoint using the new `itemSchema` media type keyword +//! introduced in OpenAPI 3.2, so consumers know the shape of each event pushed down the stream +//! - serve the endpoint for real with axum's [`axum::response::sse::Sse`] type + +use std::convert::Infallible; +use std::time::Duration; + +use axum::response::sse::{Event, KeepAlive, Sse}; +use futures_util::stream::Stream; +use rand::Rng; +use serde::Serialize; +use tokio_stream::StreamExt; +use utoipa::{OpenApi, ToSchema}; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; +use utoipa_swagger_ui::SwaggerUi; +use uuid::Uuid; + +/// A single pet status update pushed to subscribers of the `/pets/events` stream. +#[derive(Serialize, ToSchema)] +struct PetEvent { + /// Identifier of the pet the event relates to. + pet_id: Uuid, + /// New status of the pet, e.g. `"adopted"`, `"vaccinated"` or `"groomed"`. + status: String, +} + +/// Stream status updates for pets as Server-Sent Events. +/// +/// The `text/event-stream` response describes the shape of each streamed event with the +/// `item_schema` attribute, which maps to OpenAPI 3.2's `itemSchema` media type keyword. Because +/// `item_schema = PetEvent` produces a `$ref`, `PetEvent` is registered as a reusable component via +/// `#[openapi(components(schemas(PetEvent)))]` on [`ApiDoc`]. +#[utoipa::path( + get, + path = "/pets/events", + responses( + ( + status = 200, + description = "Stream of pet status updates", + content_type = "text/event-stream", + item_schema = PetEvent, + ) + ) +)] +async fn pet_events() -> Sse>> { + let uuids = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()]; + let statuses = ["vaccinated", "groomed", "adopted"]; + // Emit a finite number of events (one per second) so clients that buffer the whole + // response body + let stream = tokio_stream::iter(0u64..10) + .map(move |i| { + let mut rng = rand::thread_rng(); + let uuid_idx = rng.gen_range(0..3); + let event = PetEvent { + pet_id: uuids[uuid_idx], + status: statuses[(i % statuses.len() as u64) as usize].to_string(), + }; + Ok(Event::default().json_data(&event).unwrap()) + }) + .throttle(Duration::from_secs(1)); + + Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))) +} + +/// Opt the whole document in to OpenAPI 3.2 output with `version = "3.2.0"` +#[derive(OpenApi)] +#[openapi(version = "3.2.0", components(schemas(PetEvent)))] +struct ApiDoc; + +#[tokio::main] +async fn main() { + let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) + .routes(routes!(pet_events)) + .split_for_parts(); + + let router = router.merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", api)); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:8080") + .await + .unwrap(); + axum::serve(listener, router.into_make_service()) + .await + .unwrap(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sse_response_documents_item_schema() { + let (_, api) = OpenApiRouter::<()>::with_openapi(ApiDoc::openapi()) + .routes(routes!(pet_events)) + .split_for_parts(); + + let json = serde_json::to_value(&api).unwrap(); + + assert_eq!( + json["openapi"], + serde_json::json!("3.2.0"), + "expected document to opt in to OpenAPI 3.2, got: {}", + json["openapi"] + ); + + let content = &json["paths"]["/pets/events"]["get"]["responses"]["200"]["content"] + ["text/event-stream"]; + + assert_eq!( + content["itemSchema"]["$ref"], + serde_json::json!("#/components/schemas/PetEvent"), + "expected text/event-stream response to carry an itemSchema $ref to PetEvent, got: {content:#}" + ); + } +} diff --git a/examples/raw-json-actix/Cargo.toml b/examples/raw-json-actix/Cargo.toml index 6fa2d8f2f..a52704a0b 100644 --- a/examples/raw-json-actix/Cargo.toml +++ b/examples/raw-json-actix/Cargo.toml @@ -11,6 +11,8 @@ authors = [ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" env_logger = "0.10.0" serde_json = "1.0" diff --git a/examples/rocket-todo/Cargo.toml b/examples/rocket-todo/Cargo.toml index 5e159d07a..c8ae9e88f 100644 --- a/examples/rocket-todo/Cargo.toml +++ b/examples/rocket-todo/Cargo.toml @@ -9,6 +9,8 @@ authors = ["Elli Example "] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } rocket = { version = "0.5", features = ["json"] } utoipa = { path = "../../utoipa", features = ["rocket_extras"] } utoipa-swagger-ui = { path = "../../utoipa-swagger-ui", features = [ diff --git a/examples/simple-x-extensions/Cargo.toml b/examples/simple-x-extensions/Cargo.toml index 6bbedc5dc..9f2237684 100644 --- a/examples/simple-x-extensions/Cargo.toml +++ b/examples/simple-x-extensions/Cargo.toml @@ -5,6 +5,8 @@ version = "0.1.0" edition = "2021" [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" env_logger = "0" utoipa = { path = "../../utoipa", features = [ "yaml" ] } diff --git a/examples/simple-x-extensions/src/main.rs b/examples/simple-x-extensions/src/main.rs index 9ac424d5e..4140f8b0c 100644 --- a/examples/simple-x-extensions/src/main.rs +++ b/examples/simple-x-extensions/src/main.rs @@ -75,15 +75,19 @@ impl utoipa::Modify for ApiModify { extend_servers(&mut openapi.servers, "[Modify] openapi"); fn extend_parameters( - parameters: &mut Option>, + parameters: &mut Option>>, text: &str, ) { parameters .get_or_insert(Vec::new()) .iter_mut() - .for_each(|i| { + .filter_map(|parameter| match parameter { + utoipa::openapi::RefOr::T(parameter) => Some(parameter), + utoipa::openapi::RefOr::Ref(_) => None, + }) + .for_each(|parameter| { extend( - &mut i.extensions, + &mut parameter.extensions, format!("{text}>Parameters>item").as_str(), ); }); @@ -114,16 +118,18 @@ impl utoipa::Modify for ApiModify { ); } }); - if let Some(request_body) = &mut operation.request_body { + if let Some(utoipa::openapi::RefOr::T(request_body)) = &mut operation.request_body { extend( &mut request_body.extensions, format!("{text}>RequestBody").as_str(), ); - request_body.content.iter_mut().for_each(|(_, i)| { - extend( - &mut i.extensions, - format!("{text}>RequestBody>Content").as_str(), - ); + request_body.content.iter_mut().for_each(|(_, content)| { + if let utoipa::openapi::RefOr::T(content) = content { + extend( + &mut content.extensions, + format!("{text}>RequestBody>Content").as_str(), + ); + } }); } } diff --git a/examples/todo-actix/Cargo.toml b/examples/todo-actix/Cargo.toml index 520af46c8..4cf29a500 100644 --- a/examples/todo-actix/Cargo.toml +++ b/examples/todo-actix/Cargo.toml @@ -9,6 +9,8 @@ authors = ["Example "] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +# cookie (actix/rocket) does not build with time 0.3.52+; drop when cookie is fixed +time = { version = ">=0.3, <0.3.52" } actix-web = "4" serde = { version = "1.0", features = ["derive"] } env_logger = "0.11" diff --git a/justfile b/justfile index 48321eb55..98438c796 100644 --- a/justfile +++ b/justfile @@ -27,7 +27,7 @@ test *crates='utoipa utoipa-gen utoipa-swagger-ui utoipa-redoc utoipa-rapidoc ut $cargo $cargo_command -p utoipa-gen --test path_derive_auto_into_responses --features auto_into_responses,utoipa/uuid,uuid,utoipa/macros $cargo $cargo_command -p utoipa-gen --test path_derive_actix --test path_parameter_derive_actix --features actix_extras,utoipa/uuid,uuid,utoipa/chrono,chrono,utoipa/time,time,utoipa/macros - $cargo $cargo_command -p utoipa-gen --test path_derive_auto_into_responses_actix --features actix_extras,auto_into_responses,utoipa/uuid,uuid,utoipa/macros + $cargo $cargo_command -p utoipa-gen --test path_derive_auto_into_responses_actix --features actix_extras,auto_into_responses,utoipa/auto_into_responses,utoipa/uuid,uuid,utoipa/macros $cargo $cargo_command -p utoipa-gen --test path_derive_rocket --features rocket_extras,utoipa/macros @@ -77,7 +77,7 @@ coverage: # Generate workspace documentation (requires nightly toolchain). Output is written to target/doc/ doc: cargo +nightly doc -Z unstable-options --workspace --no-deps \ - --features actix_extras,openapi_extensions,yaml,uuid,ulid,url,non_strict_integers,actix-web,axum,rocket,macros,config \ + --features actix_extras,openapi_extensions,yaml,uuid,ulid,url,non_strict_integers,actix-web,axum,rocket,macros,config,vendored \ --config 'build.rustdocflags = ["--cfg", "doc_cfg"]' # Update vendored Swagger UI to the given version. Usage: `just update-swagger-ui 5.18.2` diff --git a/utoipa-actix-web/CHANGELOG.md b/utoipa-actix-web/CHANGELOG.md index 2572d68ed..200aea1fa 100644 --- a/utoipa-actix-web/CHANGELOG.md +++ b/utoipa-actix-web/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog - utoipa-actix-web +## 0.2 - Sep 23 2026 + +### Changed + +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) + ## 0.1.2 - Nov 8 2024 ### Added diff --git a/utoipa-actix-web/Cargo.toml b/utoipa-actix-web/Cargo.toml index 15436fb2f..91ea6dbbf 100644 --- a/utoipa-actix-web/Cargo.toml +++ b/utoipa-actix-web/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-actix-web" description = "Utoipa's actix-web bindings for seamless integration of the two" -version = "0.1.2" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -12,12 +12,12 @@ authors = ["Juha Kukkonen "] rust-version.workspace = true [dependencies] -utoipa = { package = "meteroid-utoipa", path = "../utoipa", version = "5" } +utoipa = { package = "meteroid-utoipa", path = "../utoipa", version = "6" } actix-web = { version = "4", default-features = false } actix-service = "2" [dev-dependencies] -utoipa = { package = "meteroid-utoipa", path = "../utoipa", version = "5", features = [ +utoipa = { package = "meteroid-utoipa", path = "../utoipa", version = "6", features = [ "actix_extras", "macros", "debug", @@ -29,5 +29,5 @@ serde = "1" features = [] rustdoc-args = ["--cfg", "doc_cfg"] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-actix-web/README.md b/utoipa-actix-web/README.md index 594bfa714..e937ed7f6 100644 --- a/utoipa-actix-web/README.md +++ b/utoipa-actix-web/README.md @@ -18,7 +18,7 @@ Add dependency declaration to `Cargo.toml`. ```toml [dependencies] -utoipa-actix-web = "0.1" +utoipa-actix-web = "0.2" ``` ## Examples diff --git a/utoipa-actix-web/src/lib.rs b/utoipa-actix-web/src/lib.rs index 1dedaa591..12cd6ce05 100644 --- a/utoipa-actix-web/src/lib.rs +++ b/utoipa-actix-web/src/lib.rs @@ -11,7 +11,7 @@ //! //! ```toml //! [dependencies] -//! utoipa-actix-web = "0.1" +//! utoipa-actix-web = "0.2" //! ``` //! //! ## Examples diff --git a/utoipa-actix-web/testdata/app_generated_openapi b/utoipa-actix-web/testdata/app_generated_openapi index 16373c647..26cd2a58a 100644 --- a/utoipa-actix-web/testdata/app_generated_openapi +++ b/utoipa-actix-web/testdata/app_generated_openapi @@ -10,7 +10,6 @@ "operationId": "inner_handler", "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { @@ -33,7 +32,6 @@ "operationId": "handler", "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { @@ -50,7 +48,6 @@ "operationId": "handler3", "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { @@ -67,7 +64,6 @@ "operationId": "handler2", "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-axum/CHANGELOG.md b/utoipa-axum/CHANGELOG.md index 63ce7d037..9a5e4e31c 100644 --- a/utoipa-axum/CHANGELOG.md +++ b/utoipa-axum/CHANGELOG.md @@ -1,9 +1,10 @@ # Changelog - utoipa-axum -## Unreleased +## 0.3.0 - Sep 23 2026 ### Changed +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) * Use pastey instead of unmaintained paste and fix some clippy warnings (https://github.com/juhaku/utoipa/pull/1452) ## 0.2.0 - Thu 16 2025 diff --git a/utoipa-axum/Cargo.toml b/utoipa-axum/Cargo.toml index 115895359..a021ec6fa 100644 --- a/utoipa-axum/Cargo.toml +++ b/utoipa-axum/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "meteroid-utoipa-axum" description = "Utoipa's axum bindings for seamless integration for the two (meteroid-oss fork of utoipa-axum)" -version = "0.2.0" +version = "0.3.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -29,7 +29,7 @@ debug = [] [dependencies] axum = { version = "0.8.4", default-features = false } -utoipa = { package = "meteroid-utoipa", version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { package = "meteroid-utoipa", version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } tower-service = "0.3" @@ -49,5 +49,5 @@ tower = "0.5" features = [] rustdoc-args = ["--cfg", "doc_cfg"] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-axum/README.md b/utoipa-axum/README.md index 522d6d211..843e5850e 100644 --- a/utoipa-axum/README.md +++ b/utoipa-axum/README.md @@ -19,7 +19,7 @@ Add dependency declaration to `Cargo.toml`. ```toml [dependencies] -utoipa-axum = "0.2" +utoipa-axum = "0.3" ``` ## Examples diff --git a/utoipa-axum/src/lib.rs b/utoipa-axum/src/lib.rs index dff2430ba..7377b3586 100644 --- a/utoipa-axum/src/lib.rs +++ b/utoipa-axum/src/lib.rs @@ -16,7 +16,7 @@ //! //! ```toml //! [dependencies] -//! utoipa-axum = "0.2" +//! utoipa-axum = "0.3" //! ``` //! //! ## Examples @@ -24,9 +24,10 @@ //! _**Use [`OpenApiRouter`][router] to collect handlers with _`#[utoipa::path]`_ macro to compose service and form OpenAPI spec.**_ //! //! ```rust -//! # use axum::Json; -//! # use utoipa::openapi::OpenApi; -//! # use utoipa_axum::{routes, PathItemExt, router::OpenApiRouter}; +//! use axum::Json; +//! use utoipa::openapi::OpenApi; +//! use utoipa_axum::{routes, PathItemExt, router::OpenApiRouter}; +//! //! #[derive(utoipa::ToSchema, serde::Serialize)] //! struct User { //! id: i32, diff --git a/utoipa-config/CHANGELOG.md b/utoipa-config/CHANGELOG.md index 67d9b0401..2fa04a863 100644 --- a/utoipa-config/CHANGELOG.md +++ b/utoipa-config/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog - utoipa-config +## 0.1.3 - Sep 23 2026 + +### Changed + +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) + +### Fixed + +* Fixed clippy lints (https://github.com/juhaku/utoipa/pull/1352) + ## 0.1.2 - Oct 23 2024 ### Changed @@ -30,4 +40,3 @@ * Remove commit commit id from changelogs (https://github.com/juhaku/utoipa/pull/1077) * Update to rc version * Update README.md - diff --git a/utoipa-config/Cargo.toml b/utoipa-config/Cargo.toml index d26188a5c..559495d68 100644 --- a/utoipa-config/Cargo.toml +++ b/utoipa-config/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "meteroid-utoipa-config" description = "Config for controlling utoipa's various aspects (meteroid-oss fork of utoipa-config)" -version = "0.1.2" +version = "0.1.3" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -24,5 +24,5 @@ serde_json = { version = "1.0" } features = [] rustdoc-args = ["--cfg", "doc_cfg"] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-config/config-test-crate/Cargo.toml b/utoipa-config/config-test-crate/Cargo.toml index 52a942f9e..c5f7685d4 100644 --- a/utoipa-config/config-test-crate/Cargo.toml +++ b/utoipa-config/config-test-crate/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" rust-version = "1.88" [dependencies] -utoipa = { package = "meteroid-utoipa", version = "5.0.0", path = "../../utoipa", features = [ +utoipa = { package = "meteroid-utoipa", version = "6.0.0", path = "../../utoipa", features = [ "debug", "config", ] } diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index becadff21..2273a50ba 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -4,21 +4,53 @@ ### Added +* 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) + +### Fixed + +* Mark `Option` fields with `deserialize_with` or `with` and no `default` as required (https://github.com/juhaku/utoipa/pull/1627) + +## 6.0.1 - Sep 23 2026 + +### Fixed + +* Fix min properties schema generation (https://github.com/juhaku/utoipoa/pull/1623) + +## 6.0.0 - Sep 23 2026 + +### Added + +* Add support for the media type `item_schema = ...` attribute in `responses(...)`/`request_body(...)`, mapping to OpenAPI 3.2's `itemSchema` keyword for streaming/event-based media types such as `text/event-stream` +* Add support for selecting the OpenAPI document version via the `version = "..."` attribute in `#[derive(OpenApi)]` (accepts `"3.1.0"` or `"3.2.0"`, mapping to `OpenApiVersion`) +* Add support for generic types with `IntoParams` (https://github.com/juhaku/utoipa/pull/1588) +* Add macro/derive support for OpenAPI 3.2 (https://github.com/juhaku/utoipa/pull/1555) + - Supports `summary`, `parent`, and `kind` in `#[derive(OpenApi)]` tag parsing + - Supports `querystring` and `cookie` style in path parameter parsing + - Supports `data_value` and `serialized_value` in path examples * Add `bigdecimal` and `bigdecimal_float` feature support for `BigDecimal` type (https://github.com/juhaku/utoipa/pull/1487) * Expand openAPI header fields (https://github.com/juhaku/utoipa/pull/1556) * Expand support for validation features in `#[schema(...)]` on new type structs (https://github.com/juhaku/utoipa/pull/1427) * Add quote_diagnostics! and quote_diagnostics_spanned! macros (https://github.com/juhaku/utoipa/pull/1553) * feat(gen): support Display types for security scopes (https://github.com/juhaku/utoipa/pull/1463) * Emit `title` and `default` on `RefBuilder` instead of wrapping in `oneOf` when `Option<_>` is non-nullable (https://github.com/juhaku/utoipa/pull/1380) +* Add support for extensions in `utoipa::ToSchema` named structs (https://github.com/juhaku/utoipa/pull/1593) ### Changed +* Removed support for expression ignore in `ToSchema` and `IntoParams` (https://github.com/juhaku/utoipa/pull/1619) +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) +* Update response header generation for optional schemas and content-capable headers (https://github.com/juhaku/utoipa/pull/1555) +* Adjust generated media type tokens to avoid ambiguous `Into` inference after content maps gained reference support (https://github.com/juhaku/utoipa/pull/1555) * Emit nullable_item last for OneOfBuilder (https://github.com/juhaku/utoipa/pull/1299) * Use pastey instead of unmaintained paste and fix some clippy warnings (https://github.com/juhaku/utoipa/pull/1452) ### Fixed +* Recursively discover flattened fields in maps for `#[serde(flatten)]`. (https://github.com/juhaku/utoipa/pull/1582) +* Emit `vec![...]` instead of stack allocated array literals in generated `ToSchema`/`IntoParams` code to avoid `clippy::large_stack_arrays` and stack overflows for types with many fields (https://github.com/juhaku/utoipa/issues/1454) * Avoid degenerate `oneOf` for `Option<_>` with `nullable = false` and `default`/`title`/`description` (https://github.com/juhaku/utoipa/pull/1380) +* Fix `jiff` type detection when only the `jiff_0_2` feature is enabled (https://github.com/juhaku/utoipa/pull/1575) ## 5.5.0 - May 5 2026 @@ -34,7 +66,6 @@ * Add feature support extensions in `utoipa::path` macro (https://github.com/juhaku/utoipa/pull/1292) * Add support for jiff v0.2 (https://github.com/juhaku/utoipa/pull/1332) - ## 5.3.1 - Jan 6 2025 ### Fixed diff --git a/utoipa-gen/Cargo.toml b/utoipa-gen/Cargo.toml index f5b517923..83e99e5cc 100644 --- a/utoipa-gen/Cargo.toml +++ b/utoipa-gen/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "meteroid-utoipa-gen" description = "Code generation implementation for utoipa (meteroid-oss fork of utoipa-gen)" -version = "5.6.0" +version = "6.0.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -28,7 +28,7 @@ proc-macro = true utoipa-config = { package = "meteroid-utoipa-config", version = "0.1", path = "../utoipa-config", optional = true } once_cell = { version = "1.21.4", optional = true } proc-macro2 = "1.0" -syn = { version = "2.0", features = ["full", "extra-traits"] } +syn = { version = "3", features = ["full", "extra-traits"] } quote = "1.0" regex = { version = "1.12", optional = true } uuid = { version = "1", features = ["serde"], optional = true } @@ -54,7 +54,7 @@ smallvec = { version = "1.15", features = ["serde"] } rust_decimal = { version = "1", default-features = false } bigdecimal = { version = "0.4", default-features = false } chrono = { version = "0.4", features = ["serde"] } -time = { version = "0.3", features = ["serde-human-readable"] } +time = { workspace = true, features = ["serde-human-readable"] } jiff = { version = "0.2", features = ["serde"] } serde_with = "3.14" insta = { version = "1.47", features = ["json"] } @@ -87,5 +87,5 @@ config = ["dep:utoipa-config", "dep:once_cell"] # EXPERIEMENTAL! use with cauntion auto_into_responses = [] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-gen/src/component.rs b/utoipa-gen/src/component.rs index 7f9ef253f..1913c6024 100644 --- a/utoipa-gen/src/component.rs +++ b/utoipa-gen/src/component.rs @@ -53,6 +53,9 @@ fn get_deprecated(attributes: &[Attribute]) -> Option { /// * If field has not serde's `skip_serializing_if` /// * Field has not `serde_with` double option /// * Field is not default +/// +/// An `Option` field is only checked here when it has `deserialize_with` or `with`, since serde +/// then reports a missing field instead of treating it as `None`. pub fn is_required(field_rule: &SerdeValue, container_rules: &SerdeContainer) -> bool { !field_rule.skip_serializing_if && !field_rule.double_option @@ -1576,6 +1579,7 @@ impl<'a, T> Iterator for ChildRefIter<'a, T> { #[cfg_attr(feature = "debug", derive(Debug))] pub struct FlattenedMapSchema { tokens: TokenStream, + schema_references: Vec, } impl FlattenedMapSchema { @@ -1598,7 +1602,7 @@ impl FlattenedMapSchema { // additionalProperties denoting the type // maps have 2 child schemas and we are interested the second one of them // which is used to determine the additional properties - let schema_property = ComponentSchema::new(ComponentSchemaProps { + let mut schema_property = ComponentSchema::new(ComponentSchemaProps { container, type_tree: type_tree .children @@ -1609,6 +1613,7 @@ impl FlattenedMapSchema { features, description: None, })?; + let schema_references = std::mem::take(&mut schema_property.schema_references); let schema_tokens = schema_property.to_token_stream(); tokens.extend(quote_diagnostics! { @@ -1621,7 +1626,10 @@ impl FlattenedMapSchema { example.to_tokens(&mut tokens)?; nullable.to_tokens(&mut tokens)?; - Ok(Self { tokens }) + Ok(Self { + tokens, + schema_references, + }) } } diff --git a/utoipa-gen/src/component/features.rs b/utoipa-gen/src/component/features.rs index 8a0e4ec42..3f316911e 100644 --- a/utoipa-gen/src/component/features.rs +++ b/utoipa-gen/src/component/features.rs @@ -207,7 +207,7 @@ impl ToTokensDiagnostics for Feature { quote! { .max_properties(Some(#max_properties)) } } Feature::MinProperties(min_properties) => { - quote! { .max_properties(Some(#min_properties)) } + quote! { .min_properties(Some(#min_properties)) } } Feature::SchemaWith(schema_with) => schema_with.to_token_stream(), Feature::Description(description) => quote! { .description(Some(#description)) }, diff --git a/utoipa-gen/src/component/features/attributes.rs b/utoipa-gen/src/component/features/attributes.rs index 4cb4df5d3..9448435c3 100644 --- a/utoipa-gen/src/component/features/attributes.rs +++ b/utoipa-gen/src/component/features/attributes.rs @@ -9,7 +9,7 @@ use syn::{Error, LitStr, Token, TypePath, WherePredicate}; use crate::component::serde::RenameRule; use crate::component::{schema, GenericType, TypeTree}; -use crate::parse_utils::{LitBoolOrExprPath, LitStrOrExpr}; +use crate::parse_utils::LitStrOrExpr; use crate::path::parameter::{self, ParameterStyle}; use crate::schema_type::KnownFormat; use crate::{parse_utils, AnyValue, Array, Diagnostics}; @@ -258,12 +258,12 @@ impl From for Feature { impl_feature! { #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] - pub struct Title(String); + pub struct Title(parse_utils::LitStrOrExpr); } impl Parse for Title { fn parse(input: syn::parse::ParseStream, _: Ident) -> syn::Result { - parse_utils::parse_next_literal_str(input).map(Self) + parse_utils::parse_next_literal_str_or_expr(input).map(Self) } } @@ -542,11 +542,11 @@ impl_feature! {"names" => /// Specify names of unnamed fields with `names(...) attribute for `IntoParams` derive. #[cfg_attr(feature = "debug", derive(Debug))] #[derive(Clone)] - pub struct IntoParamsNames(Vec); + pub struct IntoParamsNames(Vec); } impl IntoParamsNames { - pub fn into_values(self) -> Vec { + pub fn into_values(self) -> Vec { self.0 } } @@ -554,9 +554,9 @@ impl IntoParamsNames { impl Parse for IntoParamsNames { fn parse(input: syn::parse::ParseStream, _: Ident) -> syn::Result { Ok(Self( - parse_utils::parse_comma_separated_within_parenthesis::(input)? - .iter() - .map(LitStr::value) + parse_utils::parse_comma_separated_within_parenthesis::(input)? + .into_iter() + .map(|lit| parse_utils::LitStrOrExpr::from(lit)) .collect(), )) } @@ -1003,7 +1003,7 @@ impl_feature! { /// Ignore feature parsed from macro attributes. #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] - pub struct Ignore(pub LitBoolOrExprPath); + pub struct Ignore(pub syn::LitBool); } impl Parse for Ignore { @@ -1011,7 +1011,11 @@ impl Parse for Ignore { where Self: std::marker::Sized, { - parse_utils::parse_next_literal_bool_or_call(input).map(Self) + if input.peek(Token![=]) { + parse_utils::parse_next(input, || input.parse::()).map(Self) + } else { + Ok(true.into()) + } } } @@ -1029,7 +1033,7 @@ impl From for Feature { impl From for Ignore { fn from(value: bool) -> Self { - Self(value.into()) + Self(syn::LitBool::new(value, proc_macro2::Span::call_site())) } } diff --git a/utoipa-gen/src/component/into_params.rs b/utoipa-gen/src/component/into_params.rs index 84824a1ff..1a09f9769 100644 --- a/utoipa-gen/src/component/into_params.rs +++ b/utoipa-gen/src/component/into_params.rs @@ -4,7 +4,7 @@ use proc_macro2::TokenStream; use quote::{quote, quote_spanned, ToTokens}; use syn::{ parse::Parse, punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, Data, Field, - Generics, Ident, + GenericParam, Generics, Ident, }; use crate::{ @@ -25,9 +25,9 @@ use crate::{ FieldRename, }, doc_comment::CommentAttributes, - parse_utils::LitBoolOrExprPath, + parse_utils::LitStrOrExpr, token_stream::{quote_diagnostics, Diagnostics, ToTokensDiagnostics}, - Array, OptionExt, Required, + OptionExt, Required, }; use super::{ @@ -159,7 +159,7 @@ impl ToTokensDiagnostics for IntoParams { Ok(param.to_token_stream()) }) - .collect::, Diagnostics>>()?; + .collect::, Diagnostics>>()?; // Process flattened fields - these call into_params on the nested type let flattened_params = flattened_fields @@ -198,11 +198,12 @@ impl ToTokensDiagnostics for IntoParams { }) .collect::, Diagnostics>>()?; - // Generate the impl block + let generic_schemas = get_generic_schemas(&self.generics); tokens.extend(quote! { impl #impl_generics utoipa::IntoParams for #ident #ty_generics #where_clause { fn into_params(parameter_in_provider: impl Fn() -> Option) -> Vec { - let mut params: Vec = #direct_params + let mut generics: Vec> = vec![ #(#generic_schemas),* ]; + let mut params: Vec = vec![#(#direct_params),*] .into_iter() .filter(Option::is_some) .flatten() @@ -217,6 +218,21 @@ impl ToTokensDiagnostics for IntoParams { } } +fn get_generic_schemas(generics: &Generics) -> Vec { + generics + .params + .iter() + .filter_map(|p| { + if let GenericParam::Type(tp) = p { + let ident = tp.ident.clone(); + Some(quote! { <#ident as utoipa::PartialSchema>::schema() }) + } else { + None + } + }) + .collect::>() +} + fn parse_field_features(field: &Field) -> Result, Diagnostics> { Ok(field .attrs @@ -236,7 +252,7 @@ fn parse_field_features(field: &Field) -> Result, Diagnostics> { impl IntoParams { fn get_struct_fields( &self, - field_names: &Option<&Vec>, + field_names: &Option<&Vec>, ) -> Result, Diagnostics> { let ident = &self.ident; match &self.data { @@ -271,7 +287,7 @@ impl IntoParams { fn validate_unnamed_field_names( &self, unnamed_fields: &Punctuated, - field_names: &Option<&Vec>, + field_names: &Option<&Vec>, ) -> Option { let ident = &self.ident; match field_names { @@ -310,7 +326,7 @@ pub struct FieldParamContainerAttributes<'a> { /// See [`IntoParamsAttr::style`]. style: &'a Option, /// See [`IntoParamsAttr::names`]. The name that applies to this field. - name: Option<&'a String>, + name: Option<&'a LitStrOrExpr>, /// See [`IntoParamsAttr::parameter_in`]. parameter_in: &'a Option, /// Custom rename all if serde attribute is not present. @@ -374,25 +390,21 @@ impl Param { let mut tokens = TokenStream::new(); let field_serde_params = &field_serde_params; let ident = &field.ident; - let mut name = &*ident + let mut name = ident .as_ref() - .map(|ident| ident.to_string()) + .map(|ident| LitStrOrExpr::from(ident.to_string())) .or_else(|| container_attributes.name.cloned()) .ok_or_else(|| Diagnostics::with_span(field.span(), "No name specified for unnamed field.") .help("Try adding #[into_params(names(...))] container attribute to specify the name for this field") )?; - if name.starts_with("r#") { - name = &name[2..]; - } - let (schema_features, mut param_features) = Param::resolve_field_features(field_features, &container_attributes) .map_err(Diagnostics::from)?; let ignore = pop_feature!(param_features => Feature::Ignore(_)); - let should_always_ignore = matches!(&ignore, Some(Feature::Ignore(Ignore(LitBoolOrExprPath::LitBool(b)))) if b.value()); + let should_always_ignore = matches!(&ignore, Some(Feature::Ignore(Ignore(b))) if b.value()); if should_always_ignore { return Ok(Self { tokens: quote! { None }, @@ -408,8 +420,22 @@ impl Param { let rename_all = serde_container.rename_all.as_ref().or(container_attributes .rename_all .map(|rename_all| rename_all.as_rename_rule())); - let name = super::rename::(name, rename_to, rename_all) - .unwrap_or(Cow::Borrowed(name)); + + if let LitStrOrExpr::LitStr(s) = &name { + let lit_value = s.value(); + let value = if lit_value.starts_with("r#") { + Cow::Borrowed(&lit_value[2..]) + } else { + Cow::Borrowed(lit_value.as_str()) + }; + + name = LitStrOrExpr::from( + super::rename::(&value, rename_to, rename_all) + .unwrap_or(value) + .into_owned(), + ); + } + let type_tree = TypeTree::from_type(&field.ty)?; tokens.extend(quote! { utoipa::openapi::path::ParameterBuilder::new() @@ -450,8 +476,9 @@ impl Param { let required: Option = pop_feature!(param_features => Feature::Required(_)).into_inner(); - let component_required = - !component.is_option() && super::is_required(field_serde_params, serde_container); + let component_required = (!component.is_option() + || field_serde_params.deserialize_with) + && super::is_required(field_serde_params, serde_container); let required = match (required, component_required) { (Some(required_feature), _) => Into::::into(required_feature.is_true()), @@ -481,7 +508,7 @@ impl Param { } let tokens = match ignore { - Some(Feature::Ignore(Ignore(LitBoolOrExprPath::LitBool(bool)))) => { + Some(Feature::Ignore(Ignore(bool))) => { quote_spanned! { bool.span() => if #bool { None @@ -490,19 +517,6 @@ impl Param { } } } - Some(Feature::Ignore(Ignore(LitBoolOrExprPath::ExprPath(path)))) => { - quote_spanned! { - path.span() => { - utoipa::__dev::warn_deprecated_ignore_fn_pattern(); - - if #path() { - None - } else { - Some(#tokens) - } - } - } - } _ => quote! { Some(#tokens) }, }; diff --git a/utoipa-gen/src/component/schema.rs b/utoipa-gen/src/component/schema.rs index 191b59c41..03c870bbc 100644 --- a/utoipa-gen/src/component/schema.rs +++ b/utoipa-gen/src/component/schema.rs @@ -4,13 +4,12 @@ use proc_macro2::{Ident, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::{ parse_quote, punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, Data, Field, - Fields, FieldsNamed, FieldsUnnamed, Generics, Variant, + Fields, FieldsNamed, FieldsUnnamed, Generics, LitBool, Variant, }; use crate::{ component::features::attributes::{Rename, Title, ValueType}, doc_comment::CommentAttributes, - parse_utils::LitBoolOrExprPath, token_stream::{as_tokens_or_diagnostics, quote_diagnostics, ToTokensDiagnostics}, Array, AttributesExt, Diagnostics, OptionExt, }; @@ -322,7 +321,7 @@ struct NamedStructFieldOptions<'a> { renamed_field: Option>, required: Option, is_option: bool, - ignore: Option, + ignore: Option, } impl NamedStructSchema { @@ -366,7 +365,7 @@ impl NamedStructSchema { match field_options { Ok(Some(field_options)) => { let should_always_ignore = match &field_options.ignore { - Some(LitBoolOrExprPath::LitBool(bool)) => bool.value(), + Some(bool) => bool.value(), _ => false, }; if should_always_ignore { @@ -388,6 +387,9 @@ impl NamedStructSchema { (Property::Schema(schema), false) => { Some(std::mem::take(&mut schema.schema_references)) } + (Property::FlattenedMap(schema), false) => { + Some(std::mem::take(&mut schema.schema_references)) + } _ => None, } }) @@ -442,8 +444,8 @@ impl NamedStructSchema { let mut property_tokens = quote! { object = object.property(#name, #field_schema) }; - let component_required = - !is_option && super::is_required(field_rules, &container_rules); + let component_required = (!is_option || field_rules.deserialize_with) + && super::is_required(field_rules, &container_rules); let required = match (required, component_required) { (Some(required), _) => required.is_true(), (None, component_required) => component_required, @@ -456,20 +458,11 @@ impl NamedStructSchema { } object_tokens.extend(match ignore { - Some(LitBoolOrExprPath::LitBool(bool)) => quote_spanned! { + Some(bool) => quote_spanned! { bool.span() => if !#bool { #property_tokens; } }, - Some(LitBoolOrExprPath::ExprPath(path)) => quote_spanned! { - path.span() => { - utoipa::__dev::warn_deprecated_ignore_fn_pattern(); - - if !#path() { - #property_tokens; - } - } - }, None => quote! { #property_tokens; }, }); diff --git a/utoipa-gen/src/component/schema/enums.rs b/utoipa-gen/src/component/schema/enums.rs index aa3e157b4..db2072eb5 100644 --- a/utoipa-gen/src/component/schema/enums.rs +++ b/utoipa-gen/src/component/schema/enums.rs @@ -1076,11 +1076,10 @@ impl PlainSchema { let schema_type = schema_type.to_token_stream(); let enum_type = enum_type.as_ref(); let items = Array::Borrowed(items); - let len = items.len(); let plain_enum = quote! { .schema_type(#schema_type) - .enum_values::<[#enum_type; #len], #enum_type>(Some(#items)) + .enum_values::, #enum_type>(Some(#items)) }; Self(plain_enum.to_token_stream()) diff --git a/utoipa-gen/src/component/schema/features.rs b/utoipa-gen/src/component/schema/features.rs index f73601e7c..1fe4f7c1f 100644 --- a/utoipa-gen/src/component/schema/features.rs +++ b/utoipa-gen/src/component/schema/features.rs @@ -7,9 +7,9 @@ use crate::{ component::features::{ attributes::{ AdditionalProperties, As, Bound, ContentEncoding, ContentMediaType, Deprecated, - Description, Discriminator, Example, Examples, Format, Ignore, Inline, NoRecursion, - Nullable, ReadOnly, Rename, RenameAll, Required, SchemaWith, Title, ValueType, - WriteOnly, XmlAttr, + Description, Discriminator, Example, Examples, Extensions, Format, Ignore, Inline, + NoRecursion, Nullable, ReadOnly, Rename, RenameAll, Required, SchemaWith, Title, + ValueType, WriteOnly, XmlAttr, }, impl_into_inner, impl_merge, parse_features, validation::{ @@ -155,7 +155,8 @@ impl Parse for NamedFieldFeatures { ContentEncoding, ContentMediaType, Ignore, - NoRecursion + NoRecursion, + Extensions ))) } } diff --git a/utoipa-gen/src/component/serde.rs b/utoipa-gen/src/component/serde.rs index e20c61363..294b168ec 100644 --- a/utoipa-gen/src/component/serde.rs +++ b/utoipa-gen/src/component/serde.rs @@ -31,6 +31,7 @@ pub struct SerdeValue { pub flatten: bool, pub skip_serializing_if: bool, pub double_option: bool, + pub deserialize_with: bool, } impl SerdeValue { @@ -55,7 +56,11 @@ impl SerdeValue { TokenTree::Ident(ident) if ident == "skip_serializing_if" => { value.skip_serializing_if = true } + TokenTree::Ident(ident) if ident == "deserialize_with" => { + value.deserialize_with = true + } TokenTree::Ident(ident) if ident == "with" => { + value.deserialize_with = true; value.double_option = parse_next_lit_str(next) .and_then(|(literal, _)| { if literal == SerdeValue::SERDE_WITH_DOUBLE_OPTION { @@ -247,6 +252,9 @@ pub fn parse_value(attributes: &[Attribute]) -> Result if value.double_option { acc.double_option = value.double_option; } + if value.deserialize_with { + acc.deserialize_with = value.deserialize_with; + } acc })) diff --git a/utoipa-gen/src/lib.rs b/utoipa-gen/src/lib.rs index 0b688c12b..0965dfdcc 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -32,9 +32,9 @@ use component::into_params::IntoParams; use ext::{PathOperationResolver, PathOperations, PathResolver}; use openapi::OpenApi; use proc_macro::TokenStream; -use quote::{quote, ToTokens, TokenStreamExt}; +use quote::{quote, ToTokens}; -use proc_macro2::{Group, Ident, Punct, TokenStream as TokenStream2}; +use proc_macro2::{Ident, Punct, TokenStream as TokenStream2}; use syn::{ bracketed, parse::{Parse, ParseStream}, @@ -112,9 +112,10 @@ static CONFIG: once_cell::sync::Lazy = /// * `examples(..., ...)` Comma separated list defining multiple _`examples`_ for the schema. Each /// _`example`_ Can be any value e.g. literal, method reference or _`json!(...)`_. /// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to Structs. -/// * `title = ...` Literal string value. Can be used to define title for struct in OpenAPI +/// * `title = ...` Can be literal string or Rust expression e.g. _`const`_ reference or +/// `include_str!(...)` statement. Can be used to define title for struct in OpenAPI /// document. Some OpenAPI code generation libraries also use this field as a name for the -/// struct. +/// struct. `rename` and `rename_all` will not work in cases of passing Rust expression. /// * `rename_all = ...` Supports same syntax as _serde_ _`rename_all`_ attribute. Will rename all fields /// of the structs accordingly. If both _serde_ `rename_all` and _schema_ _`rename_all`_ are defined /// __serde__ will take precedence. @@ -162,7 +163,7 @@ static CONFIG: once_cell::sync::Lazy = /// _`Value`_ will be rendered as any OpenAPI value (i.e. no `type` restriction). /// * `inline` If the type of this field implements [`ToSchema`][to_schema], then the schema definition /// will be inlined. **warning:** Don't use this for recursive data types! -/// +/// /// **Note!**
Using `inline` with generic arguments might lead to incorrect spec generation. /// This is due to the fact that during compilation we cannot know how to treat the generic /// argument and there is difference whether it is a primitive type or another generic type. @@ -199,11 +200,11 @@ static CONFIG: once_cell::sync::Lazy = /// See [`Object::content_encoding`][schema_object_encoding] /// * `content_media_type = ...` Can be used to define MIME type of a string for underlying schema object. /// See [`Object::content_media_type`][schema_object_media_type] -/// * `ignore` or `ignore = ...` Can be used to skip the field from being serialized to OpenAPI schema. (Currently it accepts either a literal `bool` value -/// or a path to a function that returns `bool` (`Fn() -> bool`). **Note!** support for function paths is **deprecated** and will be removed in a future version.). +/// * `ignore` or `ignore = ...` Can be used to skip the field from being serialized to OpenAPI schema Only literal `bool` value is allowed. /// * `no_recursion` Is used to break from recursion in case of looping schema tree e.g. `Pet` -> /// `Owner` -> `Pet`. _`no_recursion`_ attribute must be used within `Owner` type not to allow /// recurring into `Pet`. Failing to do so will cause infinite loop and runtime **panic**. +/// * `extensions(...)` List of extensions to add to the field. See below for the format. /// /// #### Field nullability and required rules /// @@ -469,6 +470,19 @@ static CONFIG: once_cell::sync::Lazy = /// not in the code. If you'd like to mark the field as deprecated in the code as well use /// Rust's own `#[deprecated]` attribute instead. /// +/// # Extensions Requirements Attributes +/// +/// * `x-property` defines the name of the extension. +/// * `json!(...)` defines the value associated with the named extension as a `serde_json::Value`. +/// +/// **Extensions Requitement supported formats:** +/// +/// ```text +/// ("x-property" = json!({ "type": "mock" }) ), +/// ("x-an-extension" = json!({ "type": "mock" }) ), +/// ("x-another-extension" = json!( "body" ) ), +/// ``` +/// /// # Partial `#[serde(...)]` attributes support /// /// ToSchema derive has partial support for [serde attributes]. These supported attributes will reflect to the @@ -1154,6 +1168,14 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream { /// for [primitive Rust types][primitive], `application/octet-stream` for _`[u8]`_ and _`application/json`_ /// for struct and mixed enum types. /// +/// * `item_schema = ...` Optional schema describing each item of a streaming or event-based media +/// type such as `text/event-stream`, `application/jsonl` or `application/json-seq`. It maps to +/// OpenAPI 3.2's `itemSchema` media type keyword and accepts the same syntax as `body`, i.e. +/// _`item_schema = Type`_, _`item_schema = inline(Type)`_ or _`item_schema = ref("...")`_. +/// This attribute only emits the `itemSchema` keyword; opting the document in to OpenAPI 3.2 +/// output (`openapi: 3.2.0`) is a separate, deliberate step done via +/// [`OpenApiVersion::Version32`][openapi_version]. +/// /// * `headers(...)` Slice of response headers that are returned back to a caller. /// /// * `example = ...` Can be _`json!(...)`_. _`json!(...)`_ should be something that @@ -1880,6 +1902,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream { /// [into_params_derive]: derive.IntoParams.html /// [to_response_trait]: trait.ToResponse.html /// [known_format]: openapi/schema/enum.KnownFormat.html +/// [openapi_version]: openapi/enum.OpenApiVersion.html /// [xml]: openapi/xml/struct.Xml.html /// [to_schema_xml]: macro@ToSchema#xml-attribute-configuration-options /// [relative_references]: https://spec.openapis.org/oas/latest.html#relative-references-in-uris @@ -2008,6 +2031,14 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// implement [`OpenApi`][openapi] trait. Nesting allows defining one `OpenApi` per defined path. /// If more instances is defined only latest one will be rentained. /// See the _[nest(...) attribute syntax below]( #nest-attribute-syntax )_ +/// * `version = "..."` Set the [`OpenApiVersion`][openapi_version] the document serializes as. +/// Accepts a full `X.Y.Z` version string: `"3.1.0"` (the default) or `"3.2.0"`. Opt in to +/// `"3.2.0"` to emit OpenAPI 3.2 keywords. +/// * `merge(...)` Merge [`OpenApi`][openapi_struct]s into this _`OpenApi`_ instance without +/// prefixing their paths. Merge takes a comma separated list of tuples. Each _`OpenApi`_ +/// instance must implement [`OpenApi`][openapi] trait. Existing paths, schemas, responses, +/// security requirements and tags are retained; only missing items are appended. See the +/// _[merge(...) attribute syntax below]( #merge-attribute-syntax )_ /// /// /// OpenApi derive macro will also derive [`Info`][info] for OpenApi specification using Cargo @@ -2082,6 +2113,19 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// (path = "path/to/nest", api = path::to::NestableApi, tags = ["nestableapi", ...]) /// ``` /// +/// # `merge(...)` attribute syntax +/// +/// * `api = ...` Define mandatory path to struct that implements [`OpenApi`][openapi] trait. +/// * `tags = [...]` Define optional tags what are appended to the existing list of tags. +/// Unlike `nest(...)`, merge does not use the module path as a fallback tag and does not +/// rewrite paths. +/// +/// _**Example of merge definition**_ +/// ```text +/// (api = path::to::Api), +/// (api = path::to::Api, tags = ["merged", ...]) +/// ``` +/// /// # Examples /// /// _**Define OpenApi schema with some paths and components.**_ @@ -2219,8 +2263,35 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// struct ApiDoc; /// ``` /// +/// _**Merge _`UserApi`_ into the current api doc instance without a path prefix.**_ +/// ```rust +/// # use utoipa::OpenApi; +/// # +/// #[utoipa::path(get, path = "/api/v1/status")] +/// fn test_path_status() {} +/// +/// #[utoipa::path(get, path = "/test")] +/// fn user_test_path() {} +/// +/// #[derive(OpenApi)] +/// #[openapi(paths(user_test_path))] +/// struct UserApi; +/// +/// #[derive(OpenApi)] +/// #[openapi( +/// paths( +/// test_path_status +/// ), +/// merge( +/// (api = UserApi), +/// ) +/// )] +/// struct ApiDoc; +/// ``` +/// /// [openapi]: trait.OpenApi.html /// [openapi_struct]: openapi/struct.OpenApi.html +/// [openapi_version]: openapi/enum.OpenApiVersion.html /// [to_schema]: derive.ToSchema.html /// [path]: attr.path.html /// [modify]: trait.Modify.html @@ -2278,7 +2349,8 @@ pub fn openapi(input: TokenStream) -> TokenStream { /// deriving `IntoParams`: /// /// * `names(...)` Define comma separated list of names for unnamed fields of struct used as a path parameter. -/// __Only__ supported on __unnamed structs__. +/// __Only__ supported on __unnamed structs__. Can be literal string or Rust expression e.g. _`const`_ reference or +/// `include_str!(...)` statement. `rename` and `rename_all` will not work in cases of passing Rust expression. /// * `style = ...` Defines how all parameters are serialized by [`ParameterStyle`][style]. Default /// values are based on _`parameter_in`_ attribute. /// * `parameter_in = ...` = Defines where the parameters of this field are used with a value from @@ -2381,8 +2453,7 @@ pub fn openapi(input: TokenStream) -> TokenStream { /// Free form type enables use of arbitrary types within map values. /// Supports formats _`additional_properties`_ and _`additional_properties = true`_. /// -/// * `ignore` or `ignore = ...` Can be used to skip the field from being serialized to OpenAPI schema. (Currently it accepts either a literal `bool` value -/// or a path to a function that returns `bool` (`Fn() -> bool`). **Note!** support for function paths is **deprecated** and will be removed in a future version.). +/// * `ignore` or `ignore = ...` Can be used to skip the field from being serialized to OpenAPI schema Only literal `bool` value is allowed. /// /// #### Field nullability and required rules /// @@ -3164,17 +3235,18 @@ where Self::Borrowed(values) => values.iter(), }; - tokens.append(Group::new( - proc_macro2::Delimiter::Bracket, - values - .fold(Punctuated::new(), |mut punctuated, item| { - punctuated.push_value(item); - punctuated.push_punct(Punct::new(',', proc_macro2::Spacing::Alone)); - - punctuated - }) - .to_token_stream(), - )); + // Emit `vec![...]` rather than a stack array literal `[...]` to avoid + // large stack allocations for wide types (juhaku/utoipa#1454). + let items = values + .fold(Punctuated::new(), |mut punctuated, item| { + punctuated.push_value(item); + punctuated.push_punct(Punct::new(',', proc_macro2::Spacing::Alone)); + + punctuated + }) + .to_token_stream(); + + tokens.extend(quote! { vec![#items] }); } } @@ -3712,12 +3784,4 @@ mod parse_utils { } } } - - pub fn parse_next_literal_bool_or_call(input: ParseStream) -> syn::Result { - if input.peek(Token![=]) { - parse_next(input, || LitBoolOrExprPath::parse(input)) - } else { - Ok(LitBoolOrExprPath::from(true)) - } - } } diff --git a/utoipa-gen/src/openapi.rs b/utoipa-gen/src/openapi.rs index 048e764c6..999e8827f 100644 --- a/utoipa-gen/src/openapi.rs +++ b/utoipa-gen/src/openapi.rs @@ -31,6 +31,7 @@ mod info; #[cfg_attr(feature = "debug", derive(Debug))] pub struct OpenApiAttr<'o> { info: Option>, + version: Option, paths: Punctuated, components: Components, modifiers: Punctuated, @@ -39,6 +40,7 @@ pub struct OpenApiAttr<'o> { external_docs: Option, servers: Punctuated, nested: Vec, + merged: Vec, } impl<'o> OpenApiAttr<'o> { @@ -46,6 +48,9 @@ impl<'o> OpenApiAttr<'o> { if other.info.is_some() { self.info = other.info; } + if other.version.is_some() { + self.version = other.version; + } if !other.paths.is_empty() { self.paths = other.paths; } @@ -67,6 +72,8 @@ impl<'o> OpenApiAttr<'o> { if !other.servers.is_empty() { self.servers = other.servers; } + self.nested.extend(other.nested); + self.merged.extend(other.merged); self } @@ -85,6 +92,7 @@ impl Parse for OpenApiAttr<'_> { fn parse(input: syn::parse::ParseStream) -> syn::Result { const EXPECTED_ATTRIBUTE: &str = "unexpected attribute, expected any of: handlers, components, modifiers, security, tags, external_docs, servers, nest"; + "unexpected attribute, expected any of: handlers, components, modifiers, security, tags, external_docs, servers, nest, merge, version"; let mut openapi = OpenApiAttr::default(); while !input.is_empty() { @@ -99,6 +107,9 @@ impl Parse for OpenApiAttr<'_> { parenthesized!(info_stream in input); openapi.info = Some(info_stream.parse()?) } + "version" => { + openapi.version = Some(input.parse()?); + } "paths" => { openapi.paths = parse_utils::parse_comma_separated_within_parenthesis(input)?; } @@ -132,6 +143,11 @@ impl Parse for OpenApiAttr<'_> { parenthesized!(nest in input); openapi.nested = parse_utils::parse_groups_collect(&nest)?; } + "merge" => { + let merge; + parenthesized!(merge in input); + openapi.merged = parse_utils::parse_groups_collect(&merge)?; + } _ => { return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE)); } @@ -146,6 +162,55 @@ impl Parse for OpenApiAttr<'_> { } } +/// Parsed `version = "..."` attribute of `#[derive(OpenApi)]`. +/// +/// The runtime [`utoipa::openapi::OpenApiVersion`] enum lives in the `utoipa` crate and cannot be +/// referenced here (proc-macros only emit tokens and do not depend on `utoipa`). This type validates +/// the version literal at compile time and remembers which `OpenApiVersion` variant to emit. +#[cfg_attr(feature = "debug", derive(Debug))] +struct OpenApiVersionAttr { + /// Identifier of the [`utoipa::openapi::OpenApiVersion`] variant to emit, e.g. `Version32`. + variant: Ident, +} + +impl Parse for OpenApiVersionAttr { + fn parse(input: ParseStream) -> syn::Result { + let version = parse_utils::parse_next(input, || input.parse::())?; + let value = version.value(); + // Require the full `X.Y.Z` form to match the leniency of `OpenApiVersion`'s runtime + // `Deserialize`, which only accepts three dot separated segments (e.g. `3.2.0`, and any + // `3.1.x` / `3.2.x` patch). + let digits = value + .split('.') + .flat_map(|digit| digit.parse::()) + .collect::>(); + + let variant = match digits.as_slice() { + [3, 1, _] => "Version31", + [3, 2, _] => "Version32", + _ => { + return Err(syn::Error::new( + version.span(), + format!( + r#"unsupported OpenAPI version `{value}`, expected one of: "3.1.0", "3.2.0""# + ), + )) + } + }; + + Ok(Self { + variant: Ident::new(variant, version.span()), + }) + } +} + +impl ToTokens for OpenApiVersionAttr { + fn to_tokens(&self, tokens: &mut TokenStream) { + let variant = &self.variant; + tokens.extend(quote! { utoipa::openapi::OpenApiVersion::#variant }); + } +} + #[cfg_attr(feature = "debug", derive(Debug))] struct Schema(TypePath); @@ -213,14 +278,16 @@ impl Parse for Modifier { #[cfg_attr(feature = "debug", derive(Debug))] struct Tag { name: parse_utils::LitStrOrExpr, + summary: Option, description: Option, + parent: Option, + kind: Option, external_docs: Option, } impl Parse for Tag { fn parse(input: ParseStream) -> syn::Result { - const EXPECTED_ATTRIBUTE: &str = - "unexpected token, expected any of: name, description, external_docs"; + const EXPECTED_ATTRIBUTE: &str = "unexpected token, expected any of: name, summary, description, parent, kind, external_docs"; let mut tag = Tag::default(); @@ -232,9 +299,14 @@ impl Parse for Tag { match attribute_name { "name" => tag.name = parse_utils::parse_next_literal_str_or_expr(input)?, + "summary" => { + tag.summary = Some(parse_utils::parse_next_literal_str_or_expr(input)?) + } "description" => { tag.description = Some(parse_utils::parse_next_literal_str_or_expr(input)?) } + "parent" => tag.parent = Some(parse_utils::parse_next_literal_str_or_expr(input)?), + "kind" => tag.kind = Some(parse_utils::parse_next_literal_str_or_expr(input)?), "external_docs" => { let content; parenthesized!(content in input); @@ -265,6 +337,24 @@ impl ToTokens for Tag { }); } + if let Some(ref summary) = self.summary { + tokens.extend(quote! { + .summary(Some(#summary)) + }); + } + + if let Some(ref parent) = self.parent { + tokens.extend(quote! { + .parent(Some(#parent)) + }); + } + + if let Some(ref kind) = self.kind { + tokens.extend(quote! { + .kind(Some(#kind)) + }); + } + if let Some(ref external_docs) = self.external_docs { tokens.extend(quote! { .external_docs(Some(#external_docs)) @@ -279,48 +369,21 @@ pub(crate) struct OpenApi<'o>(pub Option>, pub Ident); impl OpenApi<'_> { fn nested_tokens(&self) -> Option { let nested = self.0.as_ref().map(|openapi| &openapi.nested)?; - let nest_tokens = nested.iter() - .map(|item| { - let path = &item.path; - let nest_api = &item - .open_api - .as_ref() - .expect("type path of nested api is mandatory"); - let nest_api_ident = &nest_api - .path - .segments - .last() - .expect("nest api must have at least one segment") - .ident; - let nest_api_config = format_ident!("{}Config", nest_api_ident.to_string()); - - let module_path = nest_api - .path - .segments - .iter() - .take(nest_api.path.segments.len() - 1) - .map(|segment| segment.ident.to_string()) - .collect::>() - .join("::"); - let tags = &item.tags.iter().collect::>(); - - let span = nest_api.span(); - quote_spanned! {span=> - .nest(#path, { - #[allow(non_camel_case_types)] - struct #nest_api_config; - impl utoipa::__dev::NestedApiConfig for #nest_api_config { - fn config() -> (utoipa::openapi::OpenApi, Vec<&'static str>, &'static str) { - let api = <#nest_api as utoipa::OpenApi>::openapi(); - - (api, #tags.into(), #module_path) - } - } - <#nest_api_config as utoipa::OpenApi>::openapi() - }) - } - }) - .collect::(); + let nest_tokens = nested + .iter() + .map(|item| { + let path = &item.path; + let module_path = item.reference.module_path(); + let openapi = item + .reference + .openapi_tokens("Config", quote! { #module_path }); + let span = item.reference.api.span(); + + quote_spanned! {span=> + .nest(#path, #openapi) + } + }) + .collect::(); if nest_tokens.is_empty() { None @@ -328,6 +391,28 @@ impl OpenApi<'_> { Some(nest_tokens) } } + + fn merged_tokens(&self) -> Option { + let merged = self.0.as_ref().map(|openapi| &openapi.merged)?; + let merge_tokens = merged + .iter() + .map(|item| { + // Merge keeps paths unchanged, so there is no module-path fallback tag. + let openapi = item.openapi_tokens("MergeConfig", quote! { "" }); + let span = item.api.span(); + + quote_spanned! {span=> + .merge_from(#openapi) + } + }) + .collect::(); + + if merge_tokens.is_empty() { + None + } else { + Some(merge_tokens) + } + } } impl ToTokensDiagnostics for OpenApi<'_> { @@ -401,6 +486,15 @@ impl ToTokensDiagnostics for OpenApi<'_> { _ => None, }; + let version = attributes + .as_ref() + .and_then(|attributes| attributes.version.as_ref()) + .map(|version| { + quote! { + .openapi(#version) + } + }); + let modifiers_tokens = attributes .as_ref() .map(|attributes| &attributes.modifiers) @@ -418,11 +512,17 @@ impl ToTokensDiagnostics for OpenApi<'_> { let nested_tokens = self .nested_tokens() .map(|tokens| quote! {openapi = openapi #tokens;}); + + let merged_tokens = self + .merged_tokens() + .map(|tokens| quote! {openapi = openapi #tokens;}); + tokens.extend(quote! { impl utoipa::OpenApi for #ident { fn openapi() -> utoipa::openapi::OpenApi { use utoipa::{ToSchema, Path}; let mut openapi = utoipa::openapi::OpenApiBuilder::new() + #version .info(#info) .paths({ #path_items @@ -436,6 +536,7 @@ impl ToTokensDiagnostics for OpenApi<'_> { #handler_schemas components.schemas.extend(schemas); #nested_tokens + #merged_tokens #modifiers_tokens @@ -636,55 +737,165 @@ fn impl_paths(handler_paths: Option<&Punctuated>) -> Paths { Paths(tokens, handlers) } +/// Shared `api` and optional `tags` arguments of `nest(...)` and `merge(...)`. +/// +/// The two attributes stay separate because nesting rewrites paths, while merging preserves them. +#[cfg_attr(feature = "debug", derive(Debug))] +struct OpenApiReference { + api: TypePath, + tags: Punctuated, +} + +impl OpenApiReference { + fn parse_argument( + ident: &Ident, + input: ParseStream, + api: &mut Option, + tags: &mut Punctuated, + ) -> syn::Result { + match &*ident.to_string() { + "api" => { + *api = Some(parse_utils::parse_next(input, || input.parse())?); + Ok(true) + } + "tags" => { + *tags = parse_utils::parse_next(input, || { + let tags; + bracketed!(tags in input); + Punctuated::parse_terminated(&tags) + })?; + Ok(true) + } + _ => Ok(false), + } + } + + fn from_parts( + api: Option, + tags: Punctuated, + span: proc_macro2::Span, + statement: &str, + ) -> syn::Result { + let api = api.ok_or_else(|| { + syn::Error::new( + span, + format!("`api = ...` argument is mandatory for {statement} statement"), + ) + })?; + + Ok(Self { api, tags }) + } + + fn module_path(&self) -> String { + self.api + .path + .segments + .iter() + .take(self.api.path.segments.len() - 1) + .map(|segment| segment.ident.to_string()) + .collect::>() + .join("::") + } + + fn openapi_tokens(&self, config_suffix: &str, fallback_tag: TokenStream) -> TokenStream { + let api = &self.api; + let api_ident = &api + .path + .segments + .last() + .expect("openapi reference must have at least one segment") + .ident; + let config_ident = format_ident!("{}{}", api_ident, config_suffix); + let tags = self.tags.iter().collect::>(); + let span = api.span(); + + quote_spanned! {span=> + { + #[allow(non_camel_case_types)] + struct #config_ident; + impl utoipa::__dev::NestedApiConfig for #config_ident { + fn config() -> (utoipa::openapi::OpenApi, Vec<&'static str>, &'static str) { + let api = <#api as utoipa::OpenApi>::openapi(); + + (api, #tags.into(), #fallback_tag) + } + } + <#config_ident as utoipa::OpenApi>::openapi() + } + } + } +} + +impl Parse for OpenApiReference { + fn parse(input: ParseStream) -> syn::Result { + const ERROR_MESSAGE: &str = "unexpected identifier, expected any of: api, tags"; + let mut api = None; + let mut tags = Punctuated::new(); + + while !input.is_empty() { + let ident = input.parse::().map_err(|error| { + syn::Error::new(error.span(), format!("{ERROR_MESSAGE}: {error}")) + })?; + + if !Self::parse_argument(&ident, input, &mut api, &mut tags)? { + return Err(syn::Error::new(ident.span(), ERROR_MESSAGE)); + } + + if !input.is_empty() { + input.parse::()?; + } + } + + Self::from_parts(api, tags, input.span(), "merge(...)") + } +} + /// (path = "/nest/path", api = NestApi, tags = ["tag1", "tag2"]) #[cfg_attr(feature = "debug", derive(Debug))] -#[derive(Default)] struct NestOpenApi { + reference: OpenApiReference, path: parse_utils::LitStrOrExpr, - open_api: Option, - tags: Punctuated, } impl Parse for NestOpenApi { fn parse(input: ParseStream) -> syn::Result { const ERROR_MESSAGE: &str = "unexpected identifier, expected any of: path, api, tags"; - let mut nest = NestOpenApi::default(); + let mut path = None; + let mut api = None; + let mut tags = Punctuated::new(); while !input.is_empty() { let ident = input.parse::().map_err(|error| { syn::Error::new(error.span(), format!("{ERROR_MESSAGE}: {error}")) })?; - match &*ident.to_string() { - "path" => nest.path = parse_utils::parse_next_literal_str_or_expr(input)?, - "api" => nest.open_api = Some(parse_utils::parse_next(input, || input.parse())?), - "tags" => { - nest.tags = parse_utils::parse_next(input, || { - let tags; - bracketed!(tags in input); - Punctuated::parse_terminated(&tags) - })?; - } - _ => return Err(syn::Error::new(ident.span(), ERROR_MESSAGE)), + if &*ident.to_string() == "path" { + path = Some(parse_utils::parse_next_literal_str_or_expr(input)?); + } else if !OpenApiReference::parse_argument(&ident, input, &mut api, &mut tags)? { + return Err(syn::Error::new(ident.span(), ERROR_MESSAGE)); } if !input.is_empty() { input.parse::()?; } } - if nest.path.is_empty_litstr() { - return Err(syn::Error::new( + + let path = path.ok_or_else(|| { + syn::Error::new( input.span(), "`path = ...` argument is mandatory for nest(...) statement", - )); - } - if nest.open_api.is_none() { + ) + })?; + if path.is_empty_litstr() { return Err(syn::Error::new( input.span(), - "`api = ...` argument is mandatory for nest(...) statement", + "`path = ...` argument is mandatory for nest(...) statement", )); } - Ok(nest) + Ok(Self { + reference: OpenApiReference::from_parts(api, tags, input.span(), "nest(...)")?, + path, + }) } } diff --git a/utoipa-gen/src/path.rs b/utoipa-gen/src/path.rs index 04d79af08..9de65ad46 100644 --- a/utoipa-gen/src/path.rs +++ b/utoipa-gen/src/path.rs @@ -349,13 +349,10 @@ impl<'p> ToTokensDiagnostics for Path<'p> { .path_attr .operation_id .clone() - .or(Some( - ExprLit { - attrs: vec![], - lit: Lit::Str(LitStr::new(fn_name, Span::call_site())), - } - .into(), - )) + .or(Some(Expr::Lit(ExprLit { + attrs: vec![], + lit: Lit::Str(LitStr::new(fn_name, Span::call_site())), + }))) .ok_or_else(|| { Diagnostics::new("operation id is not defined for path") .help(format!( diff --git a/utoipa-gen/src/path/example.rs b/utoipa-gen/src/path/example.rs index c15793e10..27ffb43cb 100644 --- a/utoipa-gen/src/path/example.rs +++ b/utoipa-gen/src/path/example.rs @@ -6,7 +6,7 @@ use syn::{parenthesized, Error, LitStr, Token}; use crate::{parse_utils, AnyValue}; -// (name = (summary = "...", description = "...", value = "..", external_value = "...")) +// (name = (summary = "...", description = "...", value = "..", data_value = "..", serialized_value = "..", external_value = "...")) #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct Example { @@ -14,6 +14,8 @@ pub struct Example { pub(super) summary: Option, pub(super) description: Option, pub(super) value: Option, + pub(super) data_value: Option, + pub(super) serialized_value: Option, pub(super) external_value: Option, } @@ -51,6 +53,17 @@ impl Parse for Example { AnyValue::parse_json(&content) })?) } + "data_value" => { + example.data_value = Some(parse_utils::parse_next(&content, || { + AnyValue::parse_json(&content) + })?) + } + "serialized_value" => { + example.serialized_value = Some( + parse_utils::parse_next(&content, || content.parse::())? + .value(), + ) + } "external_value" => { example.external_value = Some( parse_utils::parse_next(&content, || content.parse::())? @@ -61,7 +74,7 @@ impl Parse for Example { return Err( Error::new( ident.span(), - format!("unexpected attribute: {attribute_name}, expected one of: summary, description, value, external_value") + format!("unexpected attribute: {attribute_name}, expected one of: summary, description, value, data_value, serialized_value, external_value") ) ) } @@ -90,6 +103,14 @@ impl ToTokens for Example { .value .as_ref() .map(|value| quote!(.value(Some(#value)))); + let data_value = self + .data_value + .as_ref() + .map(|data_value| quote!(.data_value(Some(#data_value)))); + let serialized_value = self + .serialized_value + .as_ref() + .map(|serialized_value| quote!(.serialized_value(Some(#serialized_value)))); let external_value = self .external_value .as_ref() @@ -100,6 +121,8 @@ impl ToTokens for Example { #summary #description #value + #data_value + #serialized_value #external_value }) } diff --git a/utoipa-gen/src/path/media_type.rs b/utoipa-gen/src/path/media_type.rs index 5a2aeda76..a4956e398 100644 --- a/utoipa-gen/src/path/media_type.rs +++ b/utoipa-gen/src/path/media_type.rs @@ -25,16 +25,29 @@ pub mod encoding; use encoding::Encoding; -/// Parse OpenAPI Media Type object params -/// ( Schema ) -/// ( Schema = "content/type" ) -/// ( "content/type", ), -/// ( "content/type", example = ..., examples(..., ...), encoding(("exampleField" = (...)), ...), extensions(("x-ext" = json!(...))) ) +/// Parsed representation of OpenAPI Media Type object attributes. +/// +/// Maps to configuration options for request body content or response content, +/// e.g. within `responses(...)` or `request_body(...)`. +/// +/// Supports the following configuration styles: +/// * **Shorthand type form:** `Schema` (e.g. `Pet` or `inline(Pet)`) +/// * **Shorthand type + content type form:** `Schema = "content/type"` (e.g. `Pet = "application/json"`) +/// * **Shorthand content type only:** `"content/type"` (e.g. `"text/event-stream"`) +/// * **Full attribute form:** `"content/type"`, `item_schema = ...`, `example = ...`, `examples(...)`, etc. +/// +/// Supported named attributes: +/// * **item_schema** Optional schema describing each item of a streaming media type (OpenAPI 3.2 `itemSchema`). +/// * **example** Optional single example of the media type value. +/// * **examples** Optional multiple examples of the media type value. +/// * **encoding** Optional map between property names and their encoding information. +/// * **extensions** Optional custom extensions prefixing with `x-`.#[derive(Default)] #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct MediaTypeAttr<'m> { pub content_type: Option, // if none, true guess pub schema: Schema<'m>, + pub item_schema: Schema<'m>, pub example: Option, pub examples: Punctuated, pub encoding: BTreeMap, @@ -107,6 +120,10 @@ impl<'m> MediaTypeAttr<'m> { let name = &*attribute.to_string(); match name { + "item_schema" => { + let schema = parse_utils::parse_next(input, || Self::parse_schema(input))?; + self.item_schema = Schema::Default(schema); + } "example" => { self.example = Some(parse_utils::parse_next(input, || { AnyValue::parse_any(input) @@ -152,7 +169,7 @@ impl<'m> MediaTypeAttr<'m> { return Err(syn::Error::new( attribute.span(), format!( - "unexpected attribute: {unexpected}, expected any of: example, examples, encoding(...), extensions(...)" + "unexpected attribute: {unexpected}, expected any of: item_schema, example, examples, encoding(...), extensions(...)" ), )) } @@ -174,6 +191,12 @@ impl ToTokensDiagnostics for MediaTypeAttr<'_> { } else { Some(quote! { .schema(Some(#schema)) }) }; + let item_schema = &self.item_schema.try_to_token_stream()?; + let item_schema_tokens = if item_schema.is_empty() { + None + } else { + Some(quote! { .item_schema(Some(#item_schema)) }) + }; let example = self .example .as_ref() @@ -204,11 +227,11 @@ impl ToTokensDiagnostics for MediaTypeAttr<'_> { tokens.extend(quote! { utoipa::openapi::content::ContentBuilder::new() #schema_tokens + #item_schema_tokens #example #examples #(#encoding)* #extensions - .into() }); Ok(()) diff --git a/utoipa-gen/src/path/parameter.rs b/utoipa-gen/src/path/parameter.rs index 8ab583c20..514e59e90 100644 --- a/utoipa-gen/src/path/parameter.rs +++ b/utoipa-gen/src/path/parameter.rs @@ -132,7 +132,8 @@ impl<'a> From> for Parameter<'a> { ParameterIn::Query }; - let option_is_nullable = parameter_in != ParameterIn::Query; + let option_is_nullable = + !matches!(parameter_in, ParameterIn::Query | ParameterIn::QueryString); Self::Value(ValueParameter { name: argument.name.unwrap_or_else(|| Cow::Owned(String::new())), @@ -303,7 +304,10 @@ impl Parse for ValueParameter<'_> { if let Some(parameter_schema) = &mut parameter.parameter_schema { parameter_schema.features = schema_features; - if parameter.parameter_in == ParameterIn::Query { + if matches!( + parameter.parameter_in, + ParameterIn::Query | ParameterIn::QueryString + ) { parameter_schema.option_is_nullable = false; } } @@ -448,10 +452,17 @@ pub enum ParameterIn { Path, Header, Cookie, + QueryString, } impl ParameterIn { - pub const VARIANTS: &'static [Self] = &[Self::Query, Self::Path, Self::Header, Self::Cookie]; + pub const VARIANTS: &'static [Self] = &[ + Self::Query, + Self::Path, + Self::Header, + Self::Cookie, + Self::QueryString, + ]; } impl Display for ParameterIn { @@ -461,6 +472,7 @@ impl Display for ParameterIn { ParameterIn::Path => write!(f, "Path"), ParameterIn::Header => write!(f, "Header"), ParameterIn::Cookie => write!(f, "Cookie"), + ParameterIn::QueryString => write!(f, "QueryString"), } } } @@ -488,6 +500,7 @@ impl Parse for ParameterIn { "Query" => Ok(Self::Query), "Header" => Ok(Self::Header), "Cookie" => Ok(Self::Cookie), + "QueryString" => Ok(Self::QueryString), _ => Err(Error::new(style.span(), expected_style())), } } @@ -500,6 +513,7 @@ impl ToTokens for ParameterIn { Self::Query => quote! { utoipa::openapi::path::ParameterIn::Query }, Self::Header => quote! { utoipa::openapi::path::ParameterIn::Header }, Self::Cookie => quote! { utoipa::openapi::path::ParameterIn::Cookie }, + Self::QueryString => quote! { utoipa::openapi::path::ParameterIn::QueryString }, }) } } @@ -515,11 +529,12 @@ pub enum ParameterStyle { SpaceDelimited, PipeDelimited, DeepObject, + Cookie, } impl Parse for ParameterStyle { fn parse(input: ParseStream) -> syn::Result { - const EXPECTED_STYLE: &str = "unexpected style, expected one of: Matrix, Label, Form, Simple, SpaceDelimited, PipeDelimited, DeepObject"; + const EXPECTED_STYLE: &str = "unexpected style, expected one of: Matrix, Label, Form, Simple, SpaceDelimited, PipeDelimited, DeepObject, Cookie"; let style = input.parse::()?; match &*style.to_string() { @@ -530,6 +545,7 @@ impl Parse for ParameterStyle { "SpaceDelimited" => Ok(ParameterStyle::SpaceDelimited), "PipeDelimited" => Ok(ParameterStyle::PipeDelimited), "DeepObject" => Ok(ParameterStyle::DeepObject), + "Cookie" => Ok(ParameterStyle::Cookie), _ => Err(Error::new(style.span(), EXPECTED_STYLE)), } } @@ -559,6 +575,9 @@ impl ToTokens for ParameterStyle { ParameterStyle::DeepObject => { tokens.extend(quote! { utoipa::openapi::path::ParameterStyle::DeepObject }) } + ParameterStyle::Cookie => { + tokens.extend(quote! { utoipa::openapi::path::ParameterStyle::Cookie }) + } } } } diff --git a/utoipa-gen/src/path/response.rs b/utoipa-gen/src/path/response.rs index d925abf1c..cb13396e9 100644 --- a/utoipa-gen/src/path/response.rs +++ b/utoipa-gen/src/path/response.rs @@ -267,7 +267,7 @@ impl Parse for ResponseValue<'_> { impl<'r> ResponseValue<'r> { const EXPECTED_ATTRIBUTES: &'static str = - "description, body, content_type, headers, example, examples"; + "description, body, content_type, item_schema, headers, example, examples"; fn parse_named_attributes(&mut self, input: ParseStream, attribute: &Ident) -> syn::Result<()> { let attribute_name = &*attribute.to_string(); @@ -441,6 +441,7 @@ impl ToTokensDiagnostics for ResponseTuple<'_> { for media_type in value.content.iter().filter(|media_type| { !(matches!(media_type.schema, Schema::Default(DefaultSchema::None)) + && matches!(media_type.item_schema, Schema::Default(DefaultSchema::None)) && media_type.content_type.is_none()) }) { let default_content_type = media_type.schema.get_default_content_type()?; diff --git a/utoipa-gen/src/path/response/derive.rs b/utoipa-gen/src/path/response/derive.rs index f0e3df72e..76005ab69 100644 --- a/utoipa-gen/src/path/response/derive.rs +++ b/utoipa-gen/src/path/response/derive.rs @@ -208,7 +208,11 @@ impl ToTokensDiagnostics for IntoResponses { trait Response { fn to_type(ident: &Ident) -> Type { let path = Path::from(ident.clone()); - let type_path = TypePath { path, qself: None }; + let type_path = TypePath { + attrs: Vec::new(), + path, + qself: None, + }; Type::Path(type_path) } diff --git a/utoipa-gen/src/path/response/header.rs b/utoipa-gen/src/path/response/header.rs index 053e9a5be..429b2ae1c 100644 --- a/utoipa-gen/src/path/response/header.rs +++ b/utoipa-gen/src/path/response/header.rs @@ -138,7 +138,7 @@ impl ToTokensDiagnostics for Header { .to_token_stream(); tokens.extend(quote! { - utoipa::openapi::HeaderBuilder::new().schema(#media_type_schema) + utoipa::openapi::HeaderBuilder::new().schema(Some(#media_type_schema)) }) } else { // default header (string type) diff --git a/utoipa-gen/src/schema_type.rs b/utoipa-gen/src/schema_type.rs index f84acbb06..e6e5f7501 100644 --- a/utoipa-gen/src/schema_type.rs +++ b/utoipa-gen/src/schema_type.rs @@ -13,7 +13,7 @@ pub enum SchemaTypeInner { Object, /// Indicates string type of content. String, - /// Indicates integer type of content. + /// Indicates integer type of content. Integer, /// Indicates floating point number type of content. Number, @@ -70,34 +70,7 @@ impl SchemaType<'_> { }; let name = &*last_segment.ident.to_string(); - #[cfg(not(any( - feature = "chrono", - feature = "decimal", - feature = "decimal_float", - feature = "bigdecimal", - feature = "bigdecimal_float", - feature = "rocket_extras", - feature = "uuid", - feature = "ulid", - feature = "url", - feature = "time", - )))] - { - is_primitive(name) - } - - #[cfg(any( - feature = "chrono", - feature = "decimal", - feature = "decimal_float", - feature = "bigdecimal", - feature = "bigdecimal_float", - feature = "rocket_extras", - feature = "uuid", - feature = "ulid", - feature = "url", - feature = "time", - ))] + #[allow(unused_mut, reason = "mut is used in conditional compilation")] { let mut primitive = is_primitive(name); diff --git a/utoipa-gen/tests/openapi_derive.rs b/utoipa-gen/tests/openapi_derive.rs index 8e09e5575..7a059f1e6 100644 --- a/utoipa-gen/tests/openapi_derive.rs +++ b/utoipa-gen/tests/openapi_derive.rs @@ -139,6 +139,32 @@ fn derive_openapi_with_external_docs_only_url() { } } +#[test] +fn derive_openapi_default_version_is_3_1_0() { + #[derive(OpenApi)] + #[openapi()] + struct ApiDoc; + + let doc = serde_json::to_value(ApiDoc::openapi()).unwrap(); + + assert_value! {doc=> + "openapi" = r###""3.1.0""###, "Default OpenAPI version" + } +} + +#[test] +fn derive_openapi_with_version_3_2_0() { + #[derive(OpenApi)] + #[openapi(version = "3.2.0")] + struct ApiDoc; + + let doc = serde_json::to_value(ApiDoc::openapi()).unwrap(); + + assert_value! {doc=> + "openapi" = r###""3.2.0""###, "Opted-in OpenAPI 3.2 version" + } +} + #[test] fn derive_openapi_with_components_in_different_module() { mod custom { @@ -391,6 +417,188 @@ fn derive_nest_openapi_with_tags() { assert_json_snapshot!(paths); } +#[test] +fn derive_merge_openapi_with_tags() { + mod one { + use utoipa::OpenApi; + + #[derive(OpenApi)] + #[openapi(paths(api_one_handler))] + pub struct OneApi; + + #[utoipa::path(get, path = "/api/v1/one")] + #[allow(dead_code)] + fn api_one_handler() {} + } + + mod two { + use utoipa::OpenApi; + + #[derive(OpenApi)] + #[openapi(paths(api_two_handler))] + pub struct TwoApi; + + #[utoipa::path(get, path = "/api/v1/two")] + #[allow(dead_code)] + fn api_two_handler() {} + } + + mod three { + use utoipa::OpenApi; + + #[derive(OpenApi)] + #[openapi(paths(api_three_handler))] + pub struct ThreeApi; + + #[utoipa::path(get, path = "/api/v1/three")] + #[allow(dead_code)] + fn api_three_handler() {} + } + + #[derive(OpenApi)] + #[openapi( + merge( + (api = one::OneApi, tags = ["one"]), + (api = two::TwoApi, tags = ["two"]), + (api = three::ThreeApi) + ) + )] + struct ApiDoc; + + let api = serde_json::to_value(ApiDoc::openapi()).expect("should serialize to value"); + let paths = api.pointer("/paths"); + + assert_json_snapshot!(paths); +} + +#[test] +fn derive_merge_openapi_keeps_existing_items_and_appends_missing_ones() { + mod parent { + use utoipa::openapi::{RefOr, ResponseBuilder}; + use utoipa::{ToResponse, ToSchema}; + + #[derive(ToSchema)] + #[allow(dead_code)] + pub struct Shared { + parent: String, + } + + #[derive(ToSchema)] + #[allow(dead_code)] + pub struct ParentOnly { + value: String, + } + + pub struct ParentResponse; + + impl<'r> ToResponse<'r> for ParentResponse { + fn response() -> (&'r str, RefOr) { + ( + "SharedResponse", + ResponseBuilder::new().description("parent").build().into(), + ) + } + } + + #[utoipa::path(get, path = "/shared", operation_id = "parent_shared")] + #[allow(dead_code)] + fn parent_shared() {} + + #[utoipa::path(post, path = "/parent-only", operation_id = "parent_only")] + #[allow(dead_code)] + fn parent_only() {} + } + + mod merged { + use utoipa::openapi::{RefOr, ResponseBuilder}; + use utoipa::{OpenApi, ToResponse, ToSchema}; + + #[derive(ToSchema)] + #[schema(as = Shared)] + #[allow(dead_code)] + pub struct SharedOverride { + merged: String, + } + + #[derive(ToSchema)] + #[allow(dead_code)] + pub struct MergedOnly { + value: i32, + } + + pub struct MergedSharedResponse; + + impl<'r> ToResponse<'r> for MergedSharedResponse { + fn response() -> (&'r str, RefOr) { + ( + "SharedResponse", + ResponseBuilder::new().description("merged").build().into(), + ) + } + } + + pub struct ExtraResponse; + + impl<'r> ToResponse<'r> for ExtraResponse { + fn response() -> (&'r str, RefOr) { + ( + "ExtraResponse", + ResponseBuilder::new().description("extra").build().into(), + ) + } + } + + #[utoipa::path(get, path = "/shared", operation_id = "merged_shared")] + #[allow(dead_code)] + fn merged_shared() {} + + #[utoipa::path(post, path = "/shared", operation_id = "merged_shared_post")] + #[allow(dead_code)] + fn merged_shared_post() {} + + #[utoipa::path(get, path = "/merged-only", operation_id = "merged_only")] + #[allow(dead_code)] + fn merged_only() {} + + #[derive(OpenApi)] + #[openapi( + info(title = "merged title", version = "9.9.9"), + paths(merged_shared, merged_shared_post, merged_only), + components( + schemas(SharedOverride, MergedOnly), + responses(MergedSharedResponse, ExtraResponse) + ), + security( + ("parent_key" = ["read"]), + ("merged_key" = ["write"]) + ), + tags( + (name = "parent", description = "parent tag"), + (name = "merged", description = "merged tag") + ) + )] + pub struct Api; + } + + #[derive(OpenApi)] + #[openapi( + info(title = "parent title", version = "1.0.0"), + paths(parent::parent_shared, parent::parent_only), + components( + schemas(parent::Shared, parent::ParentOnly), + responses(parent::ParentResponse) + ), + security(("parent_key" = ["read"])), + tags((name = "parent", description = "parent tag")), + merge((api = merged::Api, tags = ["from-merge"])) + )] + struct ApiDoc; + + let doc = serde_json::to_value(ApiDoc::openapi()).expect("should serialize to value"); + + assert_json_snapshot!(doc); +} + #[test] fn openapi_schemas_resolve_generic_enum_schema() { #![allow(dead_code)] diff --git a/utoipa-gen/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index 15aa97f32..83d84cefb 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -911,6 +911,69 @@ fn derive_path_params_into_params_with_unit_type() { assert_json_snapshot!(parameters) } +#[test] +fn derive_parameter_rename_expr() { + const NEW_NAME: &str = "renamed_field"; + + #[derive(IntoParams)] + #[into_params(parameter_in = Path, names(NEW_NAME))] + struct Filter(#[allow(unused)] ()); + + #[utoipa::path( + get, + path = "foo", + responses( + (status = 200, description = "success response") + ), + params( + Filter + ) + )] + #[allow(unused)] + fn get_foo(query: Filter) {} + + #[derive(OpenApi, Default)] + #[openapi(paths(get_foo))] + struct ApiDoc; + + let doc = serde_json::to_value(ApiDoc::openapi()).unwrap(); + let parameters = doc.pointer("/paths/foo/get/parameters").unwrap(); + + assert_json_snapshot!(parameters) +} + +#[test] +fn derive_parameter_rename_expr_in_param_name_and_title() { + const PARAM_NAME: &str = "filter_value"; + const PARAM_TITLE: &str = "another_name"; + + #[derive(IntoParams)] + #[into_params(parameter_in = Query, names(PARAM_NAME, PARAM_TITLE))] + struct Filter(#[allow(unused)] String, #[allow(unused)] String); + + #[utoipa::path( + get, + path = "foo", + responses( + (status = 200, description = "success response") + ), + params( + Filter + ) + )] + #[allow(unused)] + fn get_foo(query: Filter) {} + + #[derive(OpenApi, Default)] + #[openapi(paths(get_foo))] + struct ApiDoc; + + let doc = serde_json::to_value(ApiDoc::openapi()).unwrap(); + let parameters = doc.pointer("/paths/foo/get/parameters").unwrap(); + + assert_json_snapshot!(parameters) +} + #[test] fn arbitrary_expr_in_operation_id() { #[utoipa::path( @@ -1143,6 +1206,35 @@ fn derive_into_params_required() { assert_json_snapshot!(value) } +#[test] +fn derive_into_params_option_with_deserialize_with_is_required() { + use serde::Deserialize; + + #[derive(IntoParams, Deserialize)] + #[into_params(parameter_in = Query)] + #[allow(unused)] + struct Params { + #[serde(deserialize_with = "Option::deserialize")] + name: Option, + #[serde(default, deserialize_with = "Option::deserialize")] + name2: Option, + name3: Option, + } + + #[utoipa::path(get, path = "/params", params(Params))] + #[allow(unused)] + fn get_params() {} + let operation = test_api_fn_doc! { + get_params, + operation: get, + path: "/params" + }; + + let value = operation.pointer("/parameters"); + + assert_json_snapshot!(value) +} + #[test] fn derive_into_params_with_serde_skip() { #[derive(IntoParams, Serialize)] @@ -1570,13 +1662,13 @@ fn derive_path_with_response_links() { get, path = "/test-links", responses( - (status = 200, description = "success response", + (status = 200, description = "success response", links( ("getFoo" = ( - operation_id = "test_links", - parameters(("key" = "value"), ("json_value" = json!(1))), - request_body = "this is body", - server(url = "http://localhost") + operation_id = "test_links", + parameters(("key" = "value"), ("json_value" = json!(1))), + request_body = "this is body", + server(url = "http://localhost") )), ("getBar" = ( operation_ref = "this is ref" @@ -1939,38 +2031,43 @@ fn derive_into_params_with_ignored_enum_field() { } #[test] -fn derive_into_params_with_ignored_struct_fn_field() { - #![allow(unused)] - - fn always_true() -> bool { - true - }; +fn derive_into_params_with_generic_field() { + #[derive(ToSchema)] + #[allow(unused)] + enum Bird { + Sparrow, + Pigeon, + Crow, + Coot, + } #[derive(ToSchema)] - struct PrivateOrPublic { - name: &'static str, + #[allow(unused)] + enum Beetle { + Stag, + Longhorn, + Weevil, } #[derive(IntoParams)] #[into_params(parameter_in = Query)] - struct Params { - value: String, - #[param(ignore = always_true)] - private_or_public: PrivateOrPublic, + #[allow(unused)] + struct QueryParams { + animal: AnimalType, } - #[utoipa::path(get, path = "/params", params(Params))] + #[utoipa::path(get, path = "/params", params(QueryParams, QueryParams))] #[allow(unused)] fn get_params() {} + let operation = test_api_fn_doc! { get_params, operation: get, path: "/params" }; + let operation = operation.pointer("/parameters"); - let value = operation.pointer("/parameters"); - - assert_json_snapshot!(value); + assert_json_snapshot!(operation); } #[test] diff --git a/utoipa-gen/tests/path_derive_auto_into_responses_actix.rs b/utoipa-gen/tests/path_derive_auto_into_responses_actix.rs index f334048bc..9ffb66943 100644 --- a/utoipa-gen/tests/path_derive_auto_into_responses_actix.rs +++ b/utoipa-gen/tests/path_derive_auto_into_responses_actix.rs @@ -1,76 +1,76 @@ #![cfg(all(feature = "auto_into_responses", feature = "actix_extras"))] +use std::fmt::Display; + use actix_web::web::{Form, Json}; use utoipa::OpenApi; use actix_web::body::BoxBody; use actix_web::http::header::ContentType; -use actix_web::{post, HttpResponse, Responder}; +use actix_web::{get, post, HttpResponse, Responder, ResponseError}; use insta::assert_json_snapshot; -// TODO this test is currently failing to compile -// -// #[test] -// fn path_operation_auto_types_responses() { -// /// Test item to to return -// #[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] -// struct Item<'s> { -// value: &'s str, -// } -// -// #[derive(utoipa::IntoResponses)] -// #[allow(unused)] -// enum ItemResponse<'s> { -// /// Item found -// #[response(status = 200)] -// Success(Item<'s>), -// /// No item found -// #[response(status = NOT_FOUND)] -// NotFound, -// } -// -// /// Error -// #[derive(Debug, utoipa::IntoResponses)] -// #[response(status = 500)] -// struct Error; -// -// impl Display for Error { -// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -// write!(f, "Error") -// } -// } -// -// impl ResponseError for Error {} -// -// impl Responder for ItemResponse<'static> { -// type Body = BoxBody; -// -// fn respond_to(self, _: &actix_web::HttpRequest) -> actix_web::HttpResponse { -// match self { -// Self::Success(item) => HttpResponse::Ok() -// .content_type(ContentType::json()) -// .body(serde_json::to_string(&item).expect("Item must serialize to json")), -// Self::NotFound => HttpResponse::NotFound().finish(), -// } -// } -// } -// -// #[utoipa::path] -// #[get("/item")] -// async fn get_item() -> Result, Error> { -// Ok(ItemResponse::Success(Item { value: "super" })) -// } -// -// #[derive(OpenApi)] -// #[openapi(paths(get_item))] -// struct ApiDoc; -// -// let doc = ApiDoc::openapi(); -// let value = serde_json::to_value(&doc).unwrap(); -// let path = value.pointer("/paths/~1item/get").unwrap(); -// -// assert_json_snapshot!(&path.pointer("/responses").unwrap()); -// } +#[test] +fn path_operation_auto_types_responses() { + /// Test item to to return + #[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] + struct Item<'s> { + value: &'s str, + } + + #[derive(utoipa::IntoResponses)] + #[allow(unused)] + enum ItemResponse<'s> { + /// Item found + #[response(status = 200)] + Success(Item<'s>), + /// No item found + #[response(status = NOT_FOUND)] + NotFound, + } + + /// Error + #[derive(Debug, utoipa::IntoResponses)] + #[response(status = 500)] + struct Error; + + impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Error") + } + } + + impl ResponseError for Error {} + + impl Responder for ItemResponse<'static> { + type Body = BoxBody; + + fn respond_to(self, _: &actix_web::HttpRequest) -> actix_web::HttpResponse { + match self { + Self::Success(item) => HttpResponse::Ok() + .content_type(ContentType::json()) + .body(serde_json::to_string(&item).expect("Item must serialize to json")), + Self::NotFound => HttpResponse::NotFound().finish(), + } + } + } + + #[utoipa::path] + #[get("/item")] + async fn get_item() -> Result, Error> { + Ok(ItemResponse::Success(Item { value: "super" })) + } + + #[derive(OpenApi)] + #[openapi(paths(get_item))] + struct ApiDoc; + + let doc = ApiDoc::openapi(); + let value = serde_json::to_value(&doc).unwrap(); + let path = value.pointer("/paths/~1item/get").unwrap(); + + assert_json_snapshot!(&path.pointer("/responses").unwrap()); +} #[test] fn path_operation_auto_types_fn_parameters() { diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 6717dddef..1f578d27c 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -104,6 +104,34 @@ fn derive_flattened_map_ref_property() { assert_json_snapshot!(map); } +#[test] +fn derive_flattened_map_ref_property_collects_recursive_schema() { + #![allow(unused)] + + #[derive(ToSchema)] + struct Bar { + value: i64, + } + + #[derive(ToSchema)] + struct Foo { + #[serde(flatten)] + data: HashMap, + } + + #[derive(OpenApi)] + #[openapi(components(schemas(Foo)))] + struct ApiDoc; + + let doc = serde_json::to_value(ApiDoc::openapi()).unwrap(); + + assert_value! { doc => + "components.schemas.Foo.additionalProperties.$ref" = r##""#/components/schemas/Bar""##, "Foo flattened map additional properties ref" + "components.schemas.Bar.type" = r#""object""#, "Bar recursively discovered type" + "components.schemas.Bar.properties.value.format" = r#""int64""#, "Bar value format" + }; +} + #[test] fn derive_enum_with_additional_properties_success() { let mode = api_doc! { @@ -164,6 +192,27 @@ fn mode_custom_default_fn() -> String { "Mode2".to_string() } +#[test] +fn derive_struct_with_extensions_success() { + let book = api_doc!( + struct Book { + #[schema( + extensions( + ("x-extension-1" = json!({ "type": "extension1" })), + ("x-extension-2" = json!({ "type": "extension2", "value": 2 })) + ) + )] + name: String, + } + ); + + assert_value! {book=> + "properties.name.x-extension-1.type" = r#""extension1""#, "Book extension 1" + "properties.name.x-extension-2.type" = r#""extension2""#, "Book extension 2" + "properties.name.x-extension-2.value" = r#"2"#, "Book extension 2 value" + } +} + #[test] fn derive_struct_with_defaults_success() { let book = api_doc! { @@ -1549,6 +1598,24 @@ fn derive_struct_with_nullable_and_required() { assert_json_snapshot!(user); } +#[test] +fn derive_struct_option_with_deserialize_with_is_required() { + use serde::Deserialize; + + let review = api_doc! { + #[derive(Deserialize)] + struct Review { + #[serde(deserialize_with = "Option::deserialize")] + app: Option, + #[serde(default, deserialize_with = "Option::deserialize")] + label: Option, + note: Option, + } + }; + + assert_json_snapshot!(review); +} + #[test] fn derive_enum_with_inline_variant() { #[allow(dead_code)] @@ -3160,27 +3227,6 @@ fn derive_schema_with_ignore_eq_false_field() { assert_json_snapshot!(value); } -#[test] -fn derive_schema_with_ignore_eq_call_field() { - #![allow(unused)] - - let value = api_doc! { - struct SchemaIgnoredField { - value: String, - #[schema(ignore = Self::ignore)] - this_is_not_private: String, - } - - impl SchemaIgnoredField { - fn ignore() -> bool { - false - } - } - }; - - assert_json_snapshot!(value); -} - #[test] fn derive_schema_with_ignore_struct() { #![allow(unused)] @@ -3215,30 +3261,6 @@ fn derive_schema_with_ignore_enum() { assert_json_snapshot!(value); } -#[test] -fn derive_schema_with_ignore_fn_struct() { - #![allow(unused)] - - fn always_true() -> bool { - true - }; - - #[derive(ToSchema)] - struct PrivateOrPublic { - name: &'static str, - } - - let value = api_doc! { - struct SchemaIgnoredField { - value: String, - #[schema(ignore = always_true)] - private_or_public: PrivateOrPublic, - } - }; - - assert_json_snapshot!(value); -} - #[test] fn derive_schema_unnamed_title() { #![allow(unused)] @@ -3651,3 +3673,64 @@ fn derive_inline_option_ref_with_nullable_false_and_default() { assert_json_snapshot!(schema); } + +// Smoke test: deriving `ToSchema` on a wide struct keeps compiling and produces +// a valid schema. Related to the large stack array fix (juhaku/utoipa#1454). +#[test] +fn derive_schema_with_many_fields_compiles() { + #![allow(unused)] + + macro_rules! wide_struct { + ($name:ident; $($field:ident),+ $(,)?) => { + #[derive(ToSchema)] + struct $name { + $($field: String,)+ + } + }; + } + + wide_struct!(WideStruct; + f000, f001, f002, f003, f004, f005, f006, f007, f008, f009, + f010, f011, f012, f013, f014, f015, f016, f017, f018, f019, + f020, f021, f022, f023, f024, f025, f026, f027, f028, f029, + f030, f031, f032, f033, f034, f035, f036, f037, f038, f039, + f040, f041, f042, f043, f044, f045, f046, f047, f048, f049, + f050, f051, f052, f053, f054, f055, f056, f057, f058, f059, + f060, f061, f062, f063, f064, f065, f066, f067, f068, f069, + f070, f071, f072, f073, f074, f075, f076, f077, f078, f079, + f080, f081, f082, f083, f084, f085, f086, f087, f088, f089, + f090, f091, f092, f093, f094, f095, f096, f097, f098, f099, + ); + + use utoipa::PartialSchema; + let schema = ::schema(); + serde_json::to_value(schema).expect("wide schema is JSON serializable"); +} + +#[test] +fn derive_correct_exclusive_min_properties() { + let schema = api_doc! { + #[schema(min_properties = 1)] + struct Foo { + property_1: Option, + property_2: Option, + } + }; + + assert_json_snapshot!(schema); +} + +#[test] +fn derive_struct_with_field_rename_expr() { + const STRUCT_TITLE: &str = "Post Title"; + + let schema = api_doc! { + #[schema(title = STRUCT_TITLE)] + struct Post { + id: i64, + description: String, + } + }; + + assert_json_snapshot!(schema); +} diff --git a/utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_keeps_existing_items_and_appends_missing_ones.snap b/utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_keeps_existing_items_and_appends_missing_ones.snap new file mode 100644 index 000000000..1f37f0cf8 --- /dev/null +++ b/utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_keeps_existing_items_and_appends_missing_ones.snap @@ -0,0 +1,124 @@ +--- +source: utoipa-gen/tests/openapi_derive.rs +expression: doc +--- +{ + "components": { + "responses": { + "ExtraResponse": { + "description": "extra" + }, + "SharedResponse": { + "description": "parent" + } + }, + "schemas": { + "MergedOnly": { + "properties": { + "value": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "value" + ], + "type": "object" + }, + "ParentOnly": { + "properties": { + "value": { + "type": "string" + } + }, + "required": [ + "value" + ], + "type": "object" + }, + "Shared": { + "properties": { + "parent": { + "type": "string" + } + }, + "required": [ + "parent" + ], + "type": "object" + } + } + }, + "info": { + "contact": { + "email": "juha7kukkonen@gmail.com", + "name": "Juha Kukkonen" + }, + "description": "Code generation implementation for utoipa (meteroid-oss fork of utoipa-gen)", + "license": { + "identifier": "MIT OR Apache-2.0", + "name": "MIT OR Apache-2.0" + }, + "title": "parent title", + "version": "1.0.0" + }, + "openapi": "3.1.0", + "paths": { + "/merged-only": { + "get": { + "operationId": "merged_only", + "responses": {}, + "tags": [ + "from-merge" + ] + } + }, + "/parent-only": { + "post": { + "operationId": "parent_only", + "responses": {}, + "tags": [ + "parent" + ] + } + }, + "/shared": { + "get": { + "operationId": "parent_shared", + "responses": {}, + "tags": [ + "parent" + ] + }, + "post": { + "operationId": "merged_shared_post", + "responses": {}, + "tags": [ + "from-merge" + ] + } + } + }, + "security": [ + { + "parent_key": [ + "read" + ] + }, + { + "merged_key": [ + "write" + ] + } + ], + "tags": [ + { + "description": "parent tag", + "name": "parent" + }, + { + "description": "merged tag", + "name": "merged" + } + ] +} diff --git a/utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_with_tags.snap b/utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_with_tags.snap new file mode 100644 index 000000000..cd653f7fe --- /dev/null +++ b/utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_with_tags.snap @@ -0,0 +1,31 @@ +--- +source: utoipa-gen/tests/openapi_derive.rs +expression: paths +--- +{ + "/api/v1/one": { + "get": { + "operationId": "api_one_handler", + "responses": {}, + "tags": [ + "one" + ] + } + }, + "/api/v1/three": { + "get": { + "operationId": "api_three_handler", + "responses": {}, + "tags": [] + } + }, + "/api/v1/two": { + "get": { + "operationId": "api_two_handler", + "responses": {}, + "tags": [ + "two" + ] + } + } +} diff --git a/utoipa-gen/tests/snapshots/openapi_derive__derive_openapi_with_generic_response.snap b/utoipa-gen/tests/snapshots/openapi_derive__derive_openapi_with_generic_response.snap index c865a3c96..bcee0101c 100644 --- a/utoipa-gen/tests/snapshots/openapi_derive__derive_openapi_with_generic_response.snap +++ b/utoipa-gen/tests/snapshots/openapi_derive__derive_openapi_with_generic_response.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/openapi_derive.rs +assertion_line: 281 expression: response -snapshot_kind: text --- { "content": { @@ -18,6 +18,5 @@ snapshot_kind: text "type": "object" } } - }, - "description": "" + } } diff --git a/utoipa-gen/tests/snapshots/path_derive__derive_into_params_option_with_deserialize_with_is_required.snap b/utoipa-gen/tests/snapshots/path_derive__derive_into_params_option_with_deserialize_with_is_required.snap new file mode 100644 index 000000000..6af4fab6d --- /dev/null +++ b/utoipa-gen/tests/snapshots/path_derive__derive_into_params_option_with_deserialize_with_is_required.snap @@ -0,0 +1,30 @@ +--- +source: utoipa-gen/tests/path_derive.rs +expression: value +--- +[ + { + "in": "query", + "name": "name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "name2", + "required": false, + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "name3", + "required": false, + "schema": { + "type": "string" + } + } +] diff --git a/utoipa-gen/tests/snapshots/path_derive__derive_into_params_with_generic_field.snap b/utoipa-gen/tests/snapshots/path_derive__derive_into_params_with_generic_field.snap new file mode 100644 index 000000000..adf3e9fed --- /dev/null +++ b/utoipa-gen/tests/snapshots/path_derive__derive_into_params_with_generic_field.snap @@ -0,0 +1,33 @@ +--- +source: utoipa-gen/tests/path_derive.rs +expression: operation +--- +[ + { + "in": "query", + "name": "animal", + "required": true, + "schema": { + "enum": [ + "Sparrow", + "Pigeon", + "Crow", + "Coot" + ], + "type": "string" + } + }, + { + "in": "query", + "name": "animal", + "required": true, + "schema": { + "enum": [ + "Stag", + "Longhorn", + "Weevil" + ], + "type": "string" + } + } +] diff --git a/utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr.snap b/utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr.snap new file mode 100644 index 000000000..209979aba --- /dev/null +++ b/utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr.snap @@ -0,0 +1,14 @@ +--- +source: utoipa-gen/tests/path_derive.rs +expression: parameters +--- +[ + { + "in": "path", + "name": "renamed_field", + "required": true, + "schema": { + "default": null + } + } +] diff --git a/utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr_in_param_name_and_title.snap b/utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr_in_param_name_and_title.snap new file mode 100644 index 000000000..a12eb12cb --- /dev/null +++ b/utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr_in_param_name_and_title.snap @@ -0,0 +1,22 @@ +--- +source: utoipa-gen/tests/path_derive.rs +expression: parameters +--- +[ + { + "in": "query", + "name": "filter_value", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "another_name", + "required": true, + "schema": { + "type": "string" + } + } +] diff --git a/utoipa-gen/tests/snapshots/path_derive__derive_path_with_response_links.snap b/utoipa-gen/tests/snapshots/path_derive__derive_path_with_response_links.snap index c4fa23d3d..7f25455c2 100644 --- a/utoipa-gen/tests/snapshots/path_derive__derive_path_with_response_links.snap +++ b/utoipa-gen/tests/snapshots/path_derive__derive_path_with_response_links.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_derive.rs +assertion_line: 1600 expression: "&paths" -snapshot_kind: text --- { "/test-links": { @@ -12,15 +12,15 @@ snapshot_kind: text "description": "success response", "links": { "getBar": { - "operation_ref": "this is ref" + "operationRef": "this is ref" }, "getFoo": { - "operation_id": "test_links", + "operationId": "test_links", "parameters": { "json_value": 1, "key": "value" }, - "request_body": "this is body", + "requestBody": "this is body", "server": { "url": "http://localhost" } diff --git a/utoipa-gen/tests/snapshots/path_derive_auto_into_responses_actix__path_operation_auto_types_responses.snap b/utoipa-gen/tests/snapshots/path_derive_auto_into_responses_actix__path_operation_auto_types_responses.snap new file mode 100644 index 000000000..a7c3f01cd --- /dev/null +++ b/utoipa-gen/tests/snapshots/path_derive_auto_into_responses_actix__path_operation_auto_types_responses.snap @@ -0,0 +1,22 @@ +--- +source: utoipa-gen/tests/path_derive_auto_into_responses_actix.rs +expression: "&path.pointer(\"/responses\").unwrap()" +--- +{ + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + }, + "description": "Item found" + }, + "404": { + "description": "No item found" + }, + "500": { + "description": "Error" + } +} diff --git a/utoipa-gen/tests/snapshots/path_derive_rocket__derive_rocket_path_with_query_params_in_option.snap b/utoipa-gen/tests/snapshots/path_derive_rocket__derive_rocket_path_with_query_params_in_option.snap index d0eb4333e..1d1ce7359 100644 --- a/utoipa-gen/tests/snapshots/path_derive_rocket__derive_rocket_path_with_query_params_in_option.snap +++ b/utoipa-gen/tests/snapshots/path_derive_rocket__derive_rocket_path_with_query_params_in_option.snap @@ -37,8 +37,7 @@ snapshot_kind: text "default": null } } - }, - "description": "" + } }, "400": { "content": { @@ -47,8 +46,7 @@ snapshot_kind: text "default": null } } - }, - "description": "" + } } } } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_examples_auto_collect_schemas-2.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_examples_auto_collect_schemas-2.snap index 90eacbb44..e3c2d0d03 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_examples_auto_collect_schemas-2.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_examples_auto_collect_schemas-2.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 351 expression: responses -snapshot_kind: text --- { "200": { @@ -26,7 +26,6 @@ snapshot_kind: text "$ref": "#/components/schemas/User" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_via_content_attribute_auto_collect_responses-2.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_via_content_attribute_auto_collect_responses-2.snap index b24f69a35..60aa4d6fc 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_via_content_attribute_auto_collect_responses-2.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_via_content_attribute_auto_collect_responses-2.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 313 expression: responses -snapshot_kind: text --- { "200": { @@ -22,7 +22,6 @@ snapshot_kind: text "$ref": "#/components/schemas/User2" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_with_multiple_examples.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_with_multiple_examples.snap index f3c2b0020..a8beb7990 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_with_multiple_examples.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__derive_path_with_multiple_responses_with_multiple_examples.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 398 expression: responses -snapshot_kind: text --- { "200": { @@ -40,7 +40,6 @@ snapshot_kind: text "$ref": "#/components/schemas/User2" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_default_no_value_nor_ref.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_default_no_value_nor_ref.snap index 88aa28e06..d8907d4bd 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_default_no_value_nor_ref.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_default_no_value_nor_ref.snap @@ -1,14 +1,12 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 459 expression: value -snapshot_kind: text --- { "operationId": "post_secret", "responses": { - "200": { - "description": "" - } + "200": {} }, "summary": "Post some secret inner handler" } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_external_ref.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_external_ref.snap index d53fc73a2..3573f3258 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_external_ref.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_external_ref.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 419 expression: responses -snapshot_kind: text --- { "200": { @@ -11,7 +11,6 @@ snapshot_kind: text "$ref": "./MyUser.json" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_inline_ref_type.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_inline_ref_type.snap index 4026e55ea..e46da53a3 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_inline_ref_type.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_inline_ref_type.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 446 expression: responses -snapshot_kind: text --- { "200": { @@ -19,7 +19,6 @@ snapshot_kind: text "type": "object" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_no_schema.snap b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_no_schema.snap index 40537af59..586010162 100644 --- a/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_no_schema.snap +++ b/utoipa-gen/tests/snapshots/path_response_derive_test__path_response_with_no_schema.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/path_response_derive_test.rs +assertion_line: 474 expression: value -snapshot_kind: text --- { "operationId": "post_secret", @@ -9,8 +9,7 @@ snapshot_kind: text "200": { "content": { "application/octet-stream": {} - }, - "description": "" + } } }, "summary": "Post some secret inner handler" diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_enum_response.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_enum_response.snap index 1b5b2a54f..fe4dcdedf 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_enum_response.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_enum_response.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 38 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_enum_with_multiple_responses.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_enum_with_multiple_responses.snap index fda10ace1..48902f273 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_enum_with_multiple_responses.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_enum_with_multiple_responses.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 336 expression: responses -snapshot_kind: text --- { "200": { @@ -30,12 +30,9 @@ snapshot_kind: text "$ref": "#/components/schemas/BadRequest" } } - }, - "description": "" - }, - "404": { - "description": "" + } }, + "404": {}, "418": { "content": { "application/json": { @@ -51,8 +48,7 @@ snapshot_kind: text "type": "object" } } - }, - "description": "" + } }, "500": { "$ref": "#/components/responses/Response" diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_inline_schema.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_inline_schema.snap index 11f335f5d..d24bce665 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_inline_schema.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_inline_schema.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 241 expression: responses -snapshot_kind: text --- { "201": { @@ -19,7 +19,6 @@ snapshot_kind: text "type": "object" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_ref_schema.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_ref_schema.snap index 84b7ae4b8..140535566 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_ref_schema.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_ref_schema.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 267 expression: responses -snapshot_kind: text --- { "201": { @@ -11,7 +11,6 @@ snapshot_kind: text "$ref": "#/components/schemas/Foo" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_to_response.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_to_response.snap index 11f335f5d..3e95f0fda 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_to_response.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_to_response.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 299 expression: responses -snapshot_kind: text --- { "201": { @@ -19,7 +19,6 @@ snapshot_kind: text "type": "object" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_with_primitive_schema.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_with_primitive_schema.snap index 1637584cb..265cb19ba 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_with_primitive_schema.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_into_responses_unnamed_struct_with_primitive_schema.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 251 expression: responses -snapshot_kind: text --- { "201": { @@ -11,7 +11,6 @@ snapshot_kind: text "type": "string" } } - }, - "description": "" + } } } diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_name_struct_response.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_name_struct_response.snap index 2cf9bd035..da6ea16ad 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_name_struct_response.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_name_struct_response.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 14 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_multiple_examples.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_multiple_examples.snap index c2abefb76..58ff48945 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_multiple_examples.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_multiple_examples.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 95 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents.snap index 695ba27b1..0152a2993 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 123 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json/1": { "schema": { diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents_inlined.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents_inlined.snap index a9d4ef807..4154c48ad 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents_inlined.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_enum_contents_inlined.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 160 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json/1": { "schema": { diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_inline_unnamed_schema.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_inline_unnamed_schema.snap index 73c266f95..c36290fe0 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_inline_unnamed_schema.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_inline_unnamed_schema.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 187 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_unit_type.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_unit_type.snap index f61f3dbdb..0bd92b766 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_unit_type.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_response_with_unit_type.snap @@ -1,8 +1,6 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 171 expression: v -snapshot_kind: text --- -{ - "description": "" -} +{} diff --git a/utoipa-gen/tests/snapshots/response_derive_test__derive_unnamed_struct_response.snap b/utoipa-gen/tests/snapshots/response_derive_test__derive_unnamed_struct_response.snap index 635aa0137..a5752735b 100644 --- a/utoipa-gen/tests/snapshots/response_derive_test__derive_unnamed_struct_response.snap +++ b/utoipa-gen/tests/snapshots/response_derive_test__derive_unnamed_struct_response.snap @@ -1,10 +1,9 @@ --- source: utoipa-gen/tests/response_derive_test.rs +assertion_line: 25 expression: v -snapshot_kind: text --- { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-gen/tests/snapshots/schema_derive_test__derive_correct_exclusive_min_properties.snap b/utoipa-gen/tests/snapshots/schema_derive_test__derive_correct_exclusive_min_properties.snap new file mode 100644 index 000000000..d20f7ec37 --- /dev/null +++ b/utoipa-gen/tests/snapshots/schema_derive_test__derive_correct_exclusive_min_properties.snap @@ -0,0 +1,22 @@ +--- +source: utoipa-gen/tests/schema_derive_test.rs +expression: schema +--- +{ + "minProperties": 1, + "properties": { + "property_1": { + "type": [ + "string", + "null" + ] + }, + "property_2": { + "type": [ + "string", + "null" + ] + } + }, + "type": "object" +} diff --git a/utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_option_with_deserialize_with_is_required.snap b/utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_option_with_deserialize_with_is_required.snap new file mode 100644 index 000000000..853f09abd --- /dev/null +++ b/utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_option_with_deserialize_with_is_required.snap @@ -0,0 +1,30 @@ +--- +source: utoipa-gen/tests/schema_derive_test.rs +expression: review +--- +{ + "properties": { + "app": { + "type": [ + "string", + "null" + ] + }, + "label": { + "type": [ + "string", + "null" + ] + }, + "note": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "app" + ], + "type": "object" +} diff --git a/utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_with_field_rename_expr.snap b/utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_with_field_rename_expr.snap new file mode 100644 index 000000000..b2855936f --- /dev/null +++ b/utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_with_field_rename_expr.snap @@ -0,0 +1,21 @@ +--- +source: utoipa-gen/tests/schema_derive_test.rs +expression: schema +--- +{ + "properties": { + "description": { + "type": "string" + }, + "id": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "id", + "description" + ], + "title": "Post Title", + "type": "object" +} diff --git a/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_collect_recursive_schema_not_inlined.snap b/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_collect_recursive_schema_not_inlined.snap index 8043cb146..74a8afb28 100644 --- a/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_collect_recursive_schema_not_inlined.snap +++ b/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_collect_recursive_schema_not_inlined.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/schema_generics.rs +assertion_line: 259 expression: api -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_enum_variants.snap b/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_enum_variants.snap index 683a1fd20..2acd4a0c6 100644 --- a/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_enum_variants.snap +++ b/utoipa-gen/tests/snapshots/schema_generics__derive_generic_schema_enum_variants.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/schema_generics.rs +assertion_line: 202 expression: api -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa-gen/tests/snapshots/schema_generics__generic_request_body_schema.snap b/utoipa-gen/tests/snapshots/schema_generics__generic_request_body_schema.snap index 2111c5f16..2c4540d9e 100644 --- a/utoipa-gen/tests/snapshots/schema_generics__generic_request_body_schema.snap +++ b/utoipa-gen/tests/snapshots/schema_generics__generic_request_body_schema.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/schema_generics.rs +assertion_line: 68 expression: doc -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa-gen/tests/snapshots/schema_generics__generic_schema_full_api.snap b/utoipa-gen/tests/snapshots/schema_generics__generic_schema_full_api.snap index c0bf8c916..f58d52de6 100644 --- a/utoipa-gen/tests/snapshots/schema_generics__generic_schema_full_api.snap +++ b/utoipa-gen/tests/snapshots/schema_generics__generic_schema_full_api.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/schema_generics.rs +assertion_line: 137 expression: doc -snapshot_kind: text --- { "openapi": "3.1.0", @@ -58,7 +58,6 @@ snapshot_kind: text }, "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { @@ -126,7 +125,6 @@ snapshot_kind: text } }, "400": { - "description": "", "content": { "application/json": { "schema": { diff --git a/utoipa-gen/tests/snapshots/schema_generics__high_order_types.snap b/utoipa-gen/tests/snapshots/schema_generics__high_order_types.snap index 749770dbd..e5c6eecb7 100644 --- a/utoipa-gen/tests/snapshots/schema_generics__high_order_types.snap +++ b/utoipa-gen/tests/snapshots/schema_generics__high_order_types.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/schema_generics.rs +assertion_line: 290 expression: api -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa-gen/tests/snapshots/schema_generics__schema_with_non_generic_root.snap b/utoipa-gen/tests/snapshots/schema_generics__schema_with_non_generic_root.snap index 3b31c83e7..fcc71abd5 100644 --- a/utoipa-gen/tests/snapshots/schema_generics__schema_with_non_generic_root.snap +++ b/utoipa-gen/tests/snapshots/schema_generics__schema_with_non_generic_root.snap @@ -1,7 +1,7 @@ --- source: utoipa-gen/tests/schema_generics.rs +assertion_line: 167 expression: api -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa-rapidoc/CHANGELOG.md b/utoipa-rapidoc/CHANGELOG.md index c9b3b169f..7ab28f2ac 100644 --- a/utoipa-rapidoc/CHANGELOG.md +++ b/utoipa-rapidoc/CHANGELOG.md @@ -1,9 +1,14 @@ # Changelog - utoipa-rapidoc +## 7.0.0 - Sep 23 2025 + +* Update utoipa to version 6.0.0 + ## 6.0.0 - Thu 16 2025 ### Changed +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) * Re-release 5.0.1 since axum upgrade is a breaking change (https://github.com/juhaku/utoipa/pull/1295) ## 5.0.1 - Jan 6 2025 diff --git a/utoipa-rapidoc/Cargo.toml b/utoipa-rapidoc/Cargo.toml index 2e423a3c9..a36e0dd49 100644 --- a/utoipa-rapidoc/Cargo.toml +++ b/utoipa-rapidoc/Cargo.toml @@ -2,7 +2,7 @@ name = "utoipa-rapidoc" description = "RapiDoc for utoipa" edition = "2021" -version = "6.0.0" +version = "7.0.0" license = "MIT OR Apache-2.0" readme = "README.md" keywords = ["rapidoc", "openapi", "documentation"] @@ -15,14 +15,19 @@ rust-version.workspace = true features = ["actix-web", "axum", "rocket"] rustdoc-args = ["--cfg", "doc_cfg"] +[features] +# Pull capped `time` with rocket so cookie 0.18.1 cannot resolve time 0.3.52+. +rocket = ["dep:rocket", "dep:time"] + [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } -utoipa = { package = "meteroid-utoipa", version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { package = "meteroid-utoipa", version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } actix-web = { version = "4", optional = true, default-features = false } rocket = { version = "0.5", features = ["json"], optional = true } +time = { workspace = true, optional = true } axum = { version = "0.8.4", default-features = false, features = [ "json", ], optional = true } @@ -30,5 +35,5 @@ axum = { version = "0.8.4", default-features = false, features = [ [dev-dependencies] utoipa-rapidoc = { path = ".", features = ["actix-web", "axum", "rocket"] } -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-rapidoc/README.md b/utoipa-rapidoc/README.md index 6fc3a4812..d0c090e5d 100644 --- a/utoipa-rapidoc/README.md +++ b/utoipa-rapidoc/README.md @@ -24,13 +24,13 @@ You may find fullsize examples from utoipa's Github [repository][examples]. Use RapiDoc only without any boiler plate implementation. ```toml [dependencies] -utoipa-rapidoc = "6" +utoipa-rapidoc = "7" ``` Enable actix-web integration with RapiDoc. ```toml [dependencies] -utoipa-rapidoc = { version = "6", features = ["actix-web"] } +utoipa-rapidoc = { version = "7", features = ["actix-web"] } ``` # Using standalone diff --git a/utoipa-rapidoc/src/lib.rs b/utoipa-rapidoc/src/lib.rs index 2459e2caa..df5085803 100644 --- a/utoipa-rapidoc/src/lib.rs +++ b/utoipa-rapidoc/src/lib.rs @@ -20,13 +20,13 @@ //! Use RapiDoc only without any boiler plate implementation. //! ```toml //! [dependencies] -//! utoipa-rapidoc = "6" +//! utoipa-rapidoc = "7" //! ``` //! //! Enable actix-web integration with RapiDoc. //! ```toml //! [dependencies] -//! utoipa-rapidoc = { version = "6", features = ["actix-web"] } +//! utoipa-rapidoc = { version = "7", features = ["actix-web"] } //! ``` //! //! # Using standalone diff --git a/utoipa-redoc/CHANGELOG.md b/utoipa-redoc/CHANGELOG.md index 50929ce57..63c791491 100644 --- a/utoipa-redoc/CHANGELOG.md +++ b/utoipa-redoc/CHANGELOG.md @@ -1,9 +1,14 @@ # Changelog - utoipa-redoc +## 7.0.0 - Sep 23 2025 + +* Update utoipa to version 6.0.0 + ## 6.0.0 - Thu 16 2025 ### Changed +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) * Re-release 5.0.1 since axum upgrade is a breaking change (https://github.com/juhaku/utoipa/pull/1295) ## 5.0.1 - Jan 6 2025 diff --git a/utoipa-redoc/Cargo.toml b/utoipa-redoc/Cargo.toml index 5e5de3a0d..98687f779 100644 --- a/utoipa-redoc/Cargo.toml +++ b/utoipa-redoc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-redoc" description = "Redoc for utoipa" -version = "6.0.0" +version = "7.0.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -15,18 +15,23 @@ rust-version.workspace = true features = ["actix-web", "axum", "rocket"] rustdoc-args = ["--cfg", "doc_cfg"] +[features] +# Pull capped `time` with rocket so cookie 0.18.1 cannot resolve time 0.3.52+. +rocket = ["dep:rocket", "dep:time"] + [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } -utoipa = { package = "meteroid-utoipa", version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { package = "meteroid-utoipa", version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } actix-web = { version = "4", optional = true } rocket = { version = "0.5", features = ["json"], optional = true } +time = { workspace = true, optional = true } axum = { version = "0.8.4", default-features = false, optional = true } [dev-dependencies] utoipa-redoc = { path = ".", features = ["actix-web", "axum", "rocket"] } -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-redoc/README.md b/utoipa-redoc/README.md index 845c66a17..d5ef6f4f0 100644 --- a/utoipa-redoc/README.md +++ b/utoipa-redoc/README.md @@ -24,13 +24,13 @@ You may find fullsize examples from utoipa's Github [repository][examples]. Use Redoc only without any boiler plate implementation. ```toml [dependencies] -utoipa-redoc = "6" +utoipa-redoc = "7" ``` Enable actix-web integration with Redoc. ```toml [dependencies] -utoipa-redoc = { version = "6", features = ["actix-web"] } +utoipa-redoc = { version = "7", features = ["actix-web"] } ``` # Using standalone diff --git a/utoipa-redoc/src/lib.rs b/utoipa-redoc/src/lib.rs index e4063aabd..51311999f 100644 --- a/utoipa-redoc/src/lib.rs +++ b/utoipa-redoc/src/lib.rs @@ -20,13 +20,13 @@ //! Use Redoc only without any boiler plate implementation. //! ```toml //! [dependencies] -//! utoipa-redoc = "6" +//! utoipa-redoc = "7" //! ``` //! //! Enable actix-web integration with Redoc. //! ```toml //! [dependencies] -//! utoipa-redoc = { version = "6", features = ["actix-web"] } +//! utoipa-redoc = { version = "7", features = ["actix-web"] } //! ``` //! //! # Using standalone diff --git a/utoipa-scalar/CHANGELOG.md b/utoipa-scalar/CHANGELOG.md index c4d3e59b6..f7f0cd94f 100644 --- a/utoipa-scalar/CHANGELOG.md +++ b/utoipa-scalar/CHANGELOG.md @@ -1,11 +1,16 @@ # Changelog - utoipa-scalar -## Unreleased +## 0.4.0 - Sep 23 2025 ### Added * Add `Scalar::title` for customizing the HTML page title (https://github.com/juhaku/utoipa/pull/1515) +### Changed + +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) +* Update utoipa to version 6.0.0 + ## 0.3.0 - Thu 16 2025 ### Changed diff --git a/utoipa-scalar/Cargo.toml b/utoipa-scalar/Cargo.toml index c06fb5c4c..436e9b52d 100644 --- a/utoipa-scalar/Cargo.toml +++ b/utoipa-scalar/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "meteroid-utoipa-scalar" description = "Scalar for utoipa (meteroid-oss fork of utoipa-scalar)" -version = "0.3.0" +version = "0.4.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -20,18 +20,23 @@ name = "utoipa_scalar" features = ["actix-web", "axum", "rocket"] rustdoc-args = ["--cfg", "doc_cfg"] +[features] +# Pull capped `time` with rocket so cookie 0.18.1 cannot resolve time 0.3.52+. +rocket = ["dep:rocket", "dep:time"] + [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } -utoipa = { package = "meteroid-utoipa", version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { package = "meteroid-utoipa", version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } actix-web = { version = "4", optional = true, default-features = false } rocket = { version = "0.5", features = ["json"], optional = true } +time = { workspace = true, optional = true } axum = { version = "0.8.4", default-features = false, optional = true } [dev-dependencies] utoipa-scalar = { package = "meteroid-utoipa-scalar", path = ".", features = ["actix-web", "axum", "rocket"] } -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-scalar/README.md b/utoipa-scalar/README.md index 6e3b5c746..bc3bd5f91 100644 --- a/utoipa-scalar/README.md +++ b/utoipa-scalar/README.md @@ -24,13 +24,13 @@ You may find fullsize examples from utoipa's Github [repository][examples]. Use Scalar only without any boiler plate implementation. ```toml [dependencies] -utoipa-scalar = "0.3" +utoipa-scalar = "0.4" ``` Enable actix-web integration with Scalar. ```toml [dependencies] -utoipa-scalar = { version = "0.3", features = ["actix-web"] } +utoipa-scalar = { version = "0.4", features = ["actix-web"] } ``` # Using standalone diff --git a/utoipa-scalar/src/lib.rs b/utoipa-scalar/src/lib.rs index fb6c3062b..a66810683 100644 --- a/utoipa-scalar/src/lib.rs +++ b/utoipa-scalar/src/lib.rs @@ -20,13 +20,13 @@ //! Use Scalar only without any boiler plate implementation. //! ```toml //! [dependencies] -//! utoipa-scalar = "0.3" +//! utoipa-scalar = "0.4" //! ``` //! //! Enable actix-web integration with Scalar. //! ```toml //! [dependencies] -//! utoipa-scalar = { version = "0.3", features = ["actix-web"] } +//! utoipa-scalar = { version = "0.4", features = ["actix-web"] } //! ``` //! //! # Using standalone diff --git a/utoipa-swagger-ui-vendored/CHANGELOG.md b/utoipa-swagger-ui-vendored/CHANGELOG.md index 4475f6f2a..b8ad80586 100644 --- a/utoipa-swagger-ui-vendored/CHANGELOG.md +++ b/utoipa-swagger-ui-vendored/CHANGELOG.md @@ -1,8 +1,10 @@ # Changelog - utoipa-swagger-ui-vendored -## Unreleased +## 0.2.0 - Sep 23 2026 ### Changed + +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) * Update Swagger UI to 5.32.6 (https://github.com/juhaku/utoipa/pull/1573) ## 0.1.2 - Oct 16 2024 diff --git a/utoipa-swagger-ui-vendored/Cargo.toml b/utoipa-swagger-ui-vendored/Cargo.toml index 186d8752b..bb2cc1a40 100644 --- a/utoipa-swagger-ui-vendored/Cargo.toml +++ b/utoipa-swagger-ui-vendored/Cargo.toml @@ -3,7 +3,7 @@ name = "utoipa-swagger-ui-vendored" description = "Vendored Swagger UI for utoipa" license = "MIT OR Apache-2.0" readme = "README.md" -version = "0.1.2" +version = "0.2.0" edition = "2021" keywords = ["swagger-ui", "vendored", "openapi", "documentation"] repository = "https://github.com/juhaku/utoipa" @@ -11,4 +11,7 @@ categories = ["web-programming"] authors = ["Juha Kukkonen "] rust-version.workspace = true +[lints] +workspace = true + [dependencies] diff --git a/utoipa-swagger-ui/CHANGELOG.md b/utoipa-swagger-ui/CHANGELOG.md index 03e933e7e..b5bc0382a 100644 --- a/utoipa-swagger-ui/CHANGELOG.md +++ b/utoipa-swagger-ui/CHANGELOG.md @@ -1,9 +1,16 @@ # Changelog - utoipa-swagger-ui -## Unreleased +## 10.0.1 - Sep 24 2026 + +### Fixed + +* Fix utoipa-swagger-ui build (https://github.com/juhaku/utoipa/pull/1624) + +## 10.0.0 - Sep 23 2026 ### Changed +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) * Update Swagger UI to 5.32.6 (https://github.com/juhaku/utoipa/pull/1573) * Add custom embedding for Swagger UI assets (https://github.com/juhaku/utoipa/pull/1570) diff --git a/utoipa-swagger-ui/Cargo.toml b/utoipa-swagger-ui/Cargo.toml index d380a505a..a7c5f74bc 100644 --- a/utoipa-swagger-ui/Cargo.toml +++ b/utoipa-swagger-ui/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-swagger-ui" description = "Swagger UI for utoipa" -version = "9.0.2" +version = "10.0.1" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -18,9 +18,11 @@ reqwest = ["dep:reqwest"] url = ["dep:url"] vendored = ["dep:utoipa-swagger-ui-vendored"] # cache swagger ui zip -cache = ["dep:dirs", "dep:sha2"] +cache = ["dep:dirs", "dep:sha2", "dep:base16ct"] minified = [] gzip = ["dep:flate2"] +# Pull capped `time` with rocket so cookie 0.18.1 cannot resolve time 0.3.52+. +rocket = ["dep:rocket", "dep:time"] [dependencies] mime_guess = { version = "2.0" } @@ -28,15 +30,17 @@ actix-web = { version = "4", optional = true, default-features = false, features "macros", ] } rocket = { version = "0.5", features = ["json"], optional = true } +# See workspace.dependencies — only enabled with `rocket` feature. +time = { workspace = true, optional = true } axum = { version = "0.8.4", default-features = false, features = [ "json", ], optional = true } -utoipa = { package = "meteroid-utoipa", version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { package = "meteroid-utoipa", version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } serde = { version = "1.0", features = ["derive", "rc"] } serde_json = { version = "1.0" } -base64 = { version = "0.22.1" } +base64 = { version = "0.23.1" } [dev-dependencies] http = "1.4" @@ -46,7 +50,7 @@ tower = "0.5" utoipa-swagger-ui = { path = ".", features = ["actix-web", "axum", "rocket"] } [package.metadata.docs.rs] -features = ["actix-web", "axum", "rocket", "vendored", "cache"] +features = ["actix-web", "axum", "rocket", "vendored"] no-default-features = true rustdoc-args = ["--cfg", "doc_cfg"] @@ -56,8 +60,9 @@ regex = "1.12" flate2 = { version = "1", optional = true } # used by cache feature -dirs = { version = "6.0", optional = true } +dirs = { version = "7.0", optional = true } sha2 = { version = "0.11", optional = true } +base16ct = { version = "1.0.0", optional = true } # enabled optionally to allow rust only build with expense of bigger dependency tree and platform # independent build. By default `curl` system package is tried for downloading the Swagger UI. @@ -66,7 +71,7 @@ reqwest = { version = "0.13", features = [ "rustls", ], default-features = false, optional = true } url = { version = "2", optional = true } -utoipa-swagger-ui-vendored = { version = "0.1", path = "../utoipa-swagger-ui-vendored", optional = true } +utoipa-swagger-ui-vendored = { version = "0.2", path = "../utoipa-swagger-ui-vendored", optional = true } -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa-swagger-ui/README.md b/utoipa-swagger-ui/README.md index 84d06b4ca..f143d4470 100644 --- a/utoipa-swagger-ui/README.md +++ b/utoipa-swagger-ui/README.md @@ -47,14 +47,14 @@ Use only the raw types without any boilerplate implementation. ```toml [dependencies] -utoipa-swagger-ui = "9" +utoipa-swagger-ui = "10" ``` Enable actix-web framework with Swagger UI you could define the dependency as follows. ```toml [dependencies] -utoipa-swagger-ui = { version = "9", features = ["actix-web"] } +utoipa-swagger-ui = { version = "10", features = ["actix-web"] } ``` **Note!** Also remember that you already have defined `utoipa` dependency in your `Cargo.toml` diff --git a/utoipa-swagger-ui/build.rs b/utoipa-swagger-ui/build.rs index 11938caa9..4da1c91b2 100644 --- a/utoipa-swagger-ui/build.rs +++ b/utoipa-swagger-ui/build.rs @@ -27,11 +27,13 @@ const SWAGGER_UI_OVERWRITE_FOLDER: &str = "SWAGGER_UI_OVERWRITE_FOLDER"; #[cfg(feature = "cache")] fn sha256(data: &[u8]) -> String { + use base16ct::HexDisplay; use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); hasher.update(data); let hash = hasher.finalize(); - format!("{hash:x}").to_uppercase() + let hex = HexDisplay(&hash); + format!("{hex:x}") } #[cfg(feature = "cache")] @@ -312,8 +314,8 @@ impl SwaggerUiDist { .map(|(relative_path, path, gzip)| { format!( r###"Asset {{ - data: include_bytes!({path:?}), - path: {relative_path:?}, + data: include_bytes!({path:?}), + path: {relative_path:?}, gzipped: {gzip} }}"### ) diff --git a/utoipa-swagger-ui/src/lib.rs b/utoipa-swagger-ui/src/lib.rs index ea71c29a0..1984e715d 100644 --- a/utoipa-swagger-ui/src/lib.rs +++ b/utoipa-swagger-ui/src/lib.rs @@ -35,13 +35,13 @@ //! Use only the raw types without any boiler plate implementation. //! ```toml //! [dependencies] -//! utoipa-swagger-ui = "9" +//! utoipa-swagger-ui = "10" //! ``` //! //! Enable actix-web framework with Swagger UI you could define the dependency as follows. //! ```toml //! [dependencies] -//! utoipa-swagger-ui = { version = "9", features = ["actix-web"] } +//! utoipa-swagger-ui = { version = "10", features = ["actix-web"] } //! ``` //! //! **Note!** Also remember that you already have defined `utoipa` dependency in your `Cargo.toml` diff --git a/utoipa/CHANGELOG.md b/utoipa/CHANGELOG.md index 89bbf7bb6..70bcf6194 100644 --- a/utoipa/CHANGELOG.md +++ b/utoipa/CHANGELOG.md @@ -3,16 +3,31 @@ **`utoipa`** is in direct correlation with **`utoipa-gen`** ([CHANGELOG.md](../utoipa-gen/CHANGELOG.md)). You might want to look into changes introduced to **`utoipa-gen`**. -## Unreleased +### Unreleased + +### Fixed + +* Fix unsigned integer known format serialization (https://github.com/juhaku/utoipa/pull/1554) + +## 6.0.0 - Sep 23 2026 ### Added +* Add support for OpenAPI 3.2.0 specification via `Version32` (https://github.com/juhaku/utoipa/pull/1555) + - Supports `$self` (`self_uri` field), `webhooks`, and `jsonSchemaDialect` on OpenAPI root + - Adds expanded components support: `mediaTypes`, `parameters`, `examples`, `requestBodies`, `headers`, `links`, `callbacks`, and `pathItems` + - Aligns OpenAPI 3.2 operation/path support: path item `$ref`, `query` operation, and `additionalOperations` + - Expands media type and streaming support: Media Type `itemSchema`, `description`, `itemEncoding`, `prefixEncoding`, and Server-Sent Events / typed streaming payload modeling + - Adds other OpenAPI 3.2 fixed fields: Tag `summary`, `parent`, and `kind`; Server `name`; XML `nodeType`; Response `summary`; Example `dataValue` and `serializedValue`; Parameter location `querystring`; Parameter style `cookie`; OAuth2 `deviceAuthorization` and `oauth2MetadataUrl`; `deprecated` on security schemes +* Correct Link Object serialization to use OpenAPI camelCase fixed fields: `operationId`, `operationRef`, and `requestBody` (https://github.com/juhaku/utoipa/pull/1555) * Add `bigdecimal` and `bigdecimal_float` feature support for `BigDecimal` type (https://github.com/juhaku/utoipa/pull/1487) * Add support for `title` on `RefBuilder` (https://github.com/juhaku/utoipa/pull/1380) * Add support for `default` on `RefBuilder` (https://github.com/juhaku/utoipa/pull/1380) ### Changed +* Removed support for expression ignore in `ToSchema` and `IntoParams` (https://github.com/juhaku/utoipa/pull/1619) +* Upgrade to Rust MSRV to 1.88 (https://github.com/juhaku/utoipa/pull/1526) * **Breaking**: Removed `serde_norway` dependency. The `yaml` feature now uses `yaml_serde` and `OpenApi::to_yaml` returns `yaml_serde::Error` (https://github.com/juhaku/utoipa/issues/1565) ## 5.5.0 - May 5 2026 diff --git a/utoipa/Cargo.toml b/utoipa/Cargo.toml index 385d90806..dd63a73de 100644 --- a/utoipa/Cargo.toml +++ b/utoipa/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "meteroid-utoipa" description = "Compile time generated OpenAPI documentation for Rust (meteroid-oss fork of utoipa)" -version = "5.6.0" +version = "6.0.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -69,7 +69,7 @@ auto_into_responses = ["utoipa-gen?/auto_into_responses"] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } yaml_serde = { version = "0.10.4", optional = true } -utoipa-gen = { package = "meteroid-utoipa-gen", version = "5.6.0", path = "../utoipa-gen", optional = true } +utoipa-gen = { package = "meteroid-utoipa-gen", version = "6.0.0", path = "../utoipa-gen", optional = true } indexmap = { version = "2", features = ["serde"] } [dev-dependencies] @@ -89,5 +89,5 @@ features = [ ] rustdoc-args = ["--cfg", "doc_cfg"] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true diff --git a/utoipa/src/lib.rs b/utoipa/src/lib.rs index ae773866a..36187aad3 100644 --- a/utoipa/src/lib.rs +++ b/utoipa/src/lib.rs @@ -134,7 +134,7 @@ //! Add dependency declaration to Cargo.toml. //! ```toml //! [dependencies] -//! utoipa = "5" +//! utoipa = "6" //! ``` //! //! # Examples @@ -1570,13 +1570,6 @@ pub mod __dev { )>, ); } - - #[deprecated( - note = "Using a function path for `ignore` is deprecated and will be removed in a future version. Use `ignore = true` or `ignore = false` instead." - )] - #[doc(hidden)] - #[allow(deprecated)] - pub fn warn_deprecated_ignore_fn_pattern() {} } #[cfg(test)] @@ -1640,8 +1633,8 @@ mod tests { assert_compact_json_snapshot!(isize::schema(), @r#"{"type": "integer"}"#); assert_compact_json_snapshot!(u8::schema(), @r#"{"type": "integer", "format": "uint8", "minimum": 0}"#); assert_compact_json_snapshot!(u16::schema(), @r#"{"type": "integer", "format": "uint16", "minimum": 0}"#); - assert_compact_json_snapshot!(u32::schema(), @r#"{"type": "integer", "format": "int32", "minimum": 0}"#); - assert_compact_json_snapshot!(u64::schema(), @r#"{"type": "integer", "format": "int64", "minimum": 0}"#); + assert_compact_json_snapshot!(u32::schema(), @r#"{"type": "integer", "format": "uint32", "minimum": 0}"#); + assert_compact_json_snapshot!(u64::schema(), @r#"{"type": "integer", "format": "uint64", "minimum": 0}"#); } #[test] diff --git a/utoipa/src/openapi.rs b/utoipa/src/openapi.rs index 62bc0ba53..0aee6ecb8 100644 --- a/utoipa/src/openapi.rs +++ b/utoipa/src/openapi.rs @@ -1,4 +1,4 @@ -//! Rust implementation of Openapi Spec V3.1. +//! Rust implementation of Openapi Spec V3.2. use serde::{ de::{Error, Expected, Visitor}, @@ -91,6 +91,17 @@ builder! { /// See more details at . pub paths: Paths, + /// Incoming requests that may be initiated by the API provider independently of an + /// incoming API request. For example, a subscription confirmation request sent to a + /// consumer-provided webhook URL after they register for notifications. + /// + /// Each key is a unique identifier for the webhook, e.g. `newPet`, and the value is a + /// [`PathItem`][path::PathItem] describing the request that the API provider will send. + /// + /// See more details at . + #[serde(skip_serializing_if = "Option::is_none")] + pub webhooks: Option, + /// Holds various reusable schemas for the OpenAPI document. /// /// Few of these elements are security schemas and object schemas. @@ -119,6 +130,14 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub external_docs: Option, + /// The default JSON Schema dialect used by Schema Objects contained within this OpenAPI + /// document. Individual [`Schema`]s may still override this by declaring their own + /// `$schema` keyword. + /// + /// See more details at . + #[serde(skip_serializing_if = "Option::is_none")] + pub json_schema_dialect: Option, + /// Schema keyword can be used to override default _`$schema`_ dialect which is by default /// “”. /// @@ -126,6 +145,13 @@ builder! { #[serde(rename = "$schema", default, skip_serializing_if = "String::is_empty")] pub schema: String, + /// URI identifying this OpenAPI document, used as the base URI for resolving relative + /// references (e.g. `$ref` values) within the document. + /// + /// See more details at . + #[serde(rename = "$self", skip_serializing_if = "Option::is_none")] + pub self_uri: Option, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -321,6 +347,25 @@ impl OpenApi { } impl OpenApiBuilder { + /// Set the [`OpenApiVersion`] the document serializes as. + /// + /// Defaults to [`OpenApiVersion::Version31`]. Set [`OpenApiVersion::Version32`] to opt in to + /// OpenAPI 3.2 output. + /// + /// # Examples + /// + /// Opt in to OpenAPI 3.2 output. + /// ```rust + /// # use utoipa::openapi::{OpenApiBuilder, OpenApiVersion, Info}; + /// let openapi = OpenApiBuilder::new() + /// .openapi(OpenApiVersion::Version32) + /// .info(Info::new("my api", "0.1.0")) + /// .build(); + /// ``` + pub fn openapi(mut self, openapi: OpenApiVersion) -> Self { + set_value!(self openapi openapi) + } + /// Add [`Info`] metadata of the API. pub fn info>(mut self, info: I) -> Self { set_value!(self info info.into()) @@ -336,6 +381,32 @@ impl OpenApiBuilder { set_value!(self paths paths.into()) } + /// Add [`Paths`] to describe incoming requests that may be initiated by the API provider. + /// + /// # Examples + /// + /// Describe a `newPet` webhook that the API provider may send to a subscriber. + /// ```rust + /// # use utoipa::openapi::{ + /// # OpenApiBuilder, Info, Paths, PathsBuilder, PathItem, HttpMethod, + /// # path::OperationBuilder, response::Response, + /// # }; + /// let openapi = OpenApiBuilder::new() + /// .info(Info::new("Events API", "1.0.0")) + /// .paths(Paths::new()) + /// .webhooks(Some(PathsBuilder::new().path( + /// "newPet", + /// PathItem::new( + /// HttpMethod::Post, + /// OperationBuilder::new().response("200", Response::new("Webhook received")), + /// ), + /// ))) + /// .build(); + /// ``` + pub fn webhooks>(mut self, webhooks: Option

) -> Self { + set_value!(self webhooks webhooks.map(Into::into)) + } + /// Add [`Components`] to configure reusable schemas. pub fn components(mut self, components: Option) -> Self { set_value!(self components components) @@ -373,6 +444,34 @@ impl OpenApiBuilder { pub fn schema>(mut self, schema: S) -> Self { set_value!(self schema schema.into()) } + + /// Add or change the default JSON Schema dialect for Schema Objects. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::OpenApiBuilder; + /// let _ = OpenApiBuilder::new() + /// .json_schema_dialect(Some("https://spec.openapis.org/oas/3.2/dialect/2025-09-17")) + /// .build(); + /// ``` + pub fn json_schema_dialect>(mut self, json_schema_dialect: Option) -> Self { + set_value!(self json_schema_dialect json_schema_dialect.map(Into::into)) + } + + /// Add or change the URI identifying this OpenAPI document. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::OpenApiBuilder; + /// let _ = OpenApiBuilder::new() + /// .self_uri(Some("https://example.com/openapi.json")) + /// .build(); + /// ``` + pub fn self_uri>(mut self, self_uri: Option) -> Self { + set_value!(self self_uri self_uri.map(Into::into)) + } } /// Represents available [OpenAPI versions][version]. @@ -381,10 +480,13 @@ impl OpenApiBuilder { #[derive(Serialize, Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub enum OpenApiVersion { - /// Will serialize to `3.1.0` the latest released OpenAPI version. + /// Will serialize to `3.1.0`, the current default OpenAPI version. #[serde(rename = "3.1.0")] #[default] Version31, + /// Will serialize to `3.2.0`. Opt-in until OpenAPI 3.2 tooling support is widespread. + #[serde(rename = "3.2.0")] + Version32, } impl<'de> Deserialize<'de> for OpenApiVersion { @@ -398,7 +500,7 @@ impl<'de> Deserialize<'de> for OpenApiVersion { type Value = OpenApiVersion; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { - formatter.write_str("a version string in 3.1.x format") + formatter.write_str("a version string in 3.1.x or 3.2.x format") } fn visit_str(self, v: &str) -> Result @@ -417,10 +519,12 @@ impl<'de> Deserialize<'de> for OpenApiVersion { .flat_map(|digit| digit.parse::()) .collect::>(); - if version.len() == 3 && version.first() == Some(&3) && version.get(1) == Some(&1) { + if matches!(version.as_slice(), [3, 1, _]) { Ok(OpenApiVersion::Version31) + } else if matches!(version.as_slice(), [3, 2, _]) { + Ok(OpenApiVersion::Version32) } else { - let expected: &dyn Expected = &"3.1.0"; + let expected: &dyn Expected = &"3.1.0 or 3.2.0"; Err(Error::invalid_value( serde::de::Unexpected::Str(&v), expected, @@ -657,19 +761,656 @@ pub(crate) use builder; #[cfg(test)] mod tests { use crate::openapi::{ + encoding::EncodingBuilder, + example::ExampleBuilder, info::InfoBuilder, - path::{OperationBuilder, PathsBuilder}, + link::LinkBuilder, + path::{ + OperationBuilder, Parameter, ParameterBuilder, ParameterIn, ParameterStyle, + PathItemBuilder, PathsBuilder, + }, + request_body::RequestBodyBuilder, + security::{DeviceAuthorization, Flow, OAuth2, Scopes, SecurityScheme}, + tag::TagBuilder, + xml::XmlBuilder, }; use insta::assert_json_snapshot; + use serde_json::json; + use std::collections::BTreeMap; use super::{response::Response, *}; #[test] fn serialize_deserialize_openapi_version_success() -> Result<(), serde_json::Error> { + assert_eq!(serde_json::to_value(&OpenApiVersion::Version32)?, "3.2.0"); assert_eq!(serde_json::to_value(&OpenApiVersion::Version31)?, "3.1.0"); + assert_eq!( + serde_json::from_str::("\"3.1.1\"")?, + OpenApiVersion::Version31 + ); + assert_eq!( + serde_json::from_str::("\"3.2.0\"")?, + OpenApiVersion::Version32 + ); Ok(()) } + #[test] + fn openapi_32_root_self_and_webhooks_serialize() { + let openapi = OpenApiBuilder::new() + .openapi(OpenApiVersion::Version32) + .info(Info::new("Events API", "1.0.0")) + .json_schema_dialect(Some("https://spec.openapis.org/oas/3.2/dialect/2025-09-17")) + .self_uri(Some("https://example.com/openapi.json")) + .paths(Paths::new()) + .webhooks(Some(PathsBuilder::new().path( + "newPet", + PathItem::new( + HttpMethod::Post, + OperationBuilder::new().response("200", Response::new("Webhook received")), + ), + ))) + .build(); + + assert_eq!( + serde_json::to_value(openapi).unwrap(), + json!({ + "openapi": "3.2.0", + "$self": "https://example.com/openapi.json", + "jsonSchemaDialect": "https://spec.openapis.org/oas/3.2/dialect/2025-09-17", + "info": { + "title": "Events API", + "version": "1.0.0" + }, + "paths": {}, + "webhooks": { + "newPet": { + "post": { + "responses": { + "200": { + "description": "Webhook received" + } + } + } + } + } + }) + ); + } + + #[test] + fn openapi_32_components_and_callbacks_use_spec_data_model() { + let callback_path = PathItemBuilder::new() + .query(Some( + OperationBuilder::new().response("200", ResponseBuilder::new()), + )) + .build(); + let operation = OperationBuilder::new() + .callback( + "onEvent", + BTreeMap::from([( + "{$request.body#/callbackUrl}".to_string(), + callback_path.clone().into(), + )]), + ) + .response("202", ResponseBuilder::new().summary(Some("Accepted"))) + .build(); + let components = ComponentsBuilder::new() + .parameter( + "Limit", + ParameterBuilder::new() + .name("limit") + .parameter_in(ParameterIn::Query) + .schema(Some(ObjectBuilder::new().schema_type(Type::Integer))) + .build(), + ) + .example( + "Accepted", + ExampleBuilder::new().summary("Accepted").build(), + ) + .request_body( + "EventRequest", + RequestBodyBuilder::new() + .content( + "application/json", + ContentBuilder::new() + .schema(Some(Ref::from_schema_name("EventPayload"))) + .build(), + ) + .build(), + ) + .header( + "RateLimit", + HeaderBuilder::new() + .schema(Some(ObjectBuilder::new().schema_type(Type::Integer))) + .build(), + ) + .link( + "GetEvent", + LinkBuilder::new().operation_id("getEvent").build(), + ) + .callback( + "EventCallback", + BTreeMap::from([( + "{$request.body#/callbackUrl}".to_string(), + callback_path.clone().into(), + )]), + ) + .path_item("EventPath", callback_path) + .media_type( + "SseEvent", + ContentBuilder::new() + .description(Some("Server-sent event item")) + .item_schema(Some(Ref::from_schema_name("ServerEvent"))) + .item_encoding(Some( + EncodingBuilder::new().content_type(Some("application/json")), + )) + .prefix_encoding([EncodingBuilder::new().content_type(Some("text/plain"))]) + .build(), + ) + .security_scheme("ApiKey", RefOr::Ref(Ref::from_schema_name("ApiKey"))) + .build(); + + assert_eq!( + serde_json::to_value(operation).unwrap(), + json!({ + "responses": { + "202": { + "summary": "Accepted" + } + }, + "callbacks": { + "onEvent": { + "{$request.body#/callbackUrl}": { + "query": { + "responses": { + "200": {} + } + } + } + } + } + }) + ); + assert_eq!( + serde_json::to_value(components).unwrap(), + json!({ + "parameters": { + "Limit": { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer" + } + } + }, + "examples": { + "Accepted": { + "summary": "Accepted" + } + }, + "requestBodies": { + "EventRequest": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EventPayload" + } + } + } + } + }, + "headers": { + "RateLimit": { + "schema": { + "type": "integer" + } + } + }, + "links": { + "GetEvent": { + "operationId": "getEvent" + } + }, + "callbacks": { + "EventCallback": { + "{$request.body#/callbackUrl}": { + "query": { + "responses": { + "200": {} + } + } + } + } + }, + "pathItems": { + "EventPath": { + "query": { + "responses": { + "200": {} + } + } + } + }, + "mediaTypes": { + "SseEvent": { + "description": "Server-sent event item", + "itemSchema": { + "$ref": "#/components/schemas/ServerEvent" + }, + "prefixEncoding": [ + { + "contentType": "text/plain" + } + ], + "itemEncoding": { + "contentType": "application/json" + } + } + }, + "securitySchemes": { + "ApiKey": { + "$ref": "#/components/schemas/ApiKey" + } + } + }) + ); + } + + #[test] + fn openapi_32_tags_server_xml_and_examples_serialize() { + let tag = TagBuilder::new() + .name("partner") + .summary(Some("Partner")) + .description(Some("Operations available to partners")) + .parent(Some("external")) + .kind(Some("audience")) + .build(); + let server = ServerBuilder::new() + .url("https://api.example.com") + .name(Some("production")) + .build(); + let xml = XmlBuilder::new() + .name(Some("animal")) + .node_type(Some("element")) + .build(); + let example = ExampleBuilder::new() + .summary("Serialized query") + .data_value(Some(json!({"flag": true}))) + .serialized_value(Some("flag=true")) + .build(); + + assert_eq!( + serde_json::to_value(tag).unwrap(), + json!({ + "name": "partner", + "summary": "Partner", + "description": "Operations available to partners", + "parent": "external", + "kind": "audience" + }) + ); + assert_eq!( + serde_json::to_value(server).unwrap(), + json!({ + "url": "https://api.example.com", + "name": "production" + }) + ); + assert_eq!( + serde_json::to_value(xml).unwrap(), + json!({ + "name": "animal", + "nodeType": "element" + }) + ); + assert_eq!( + serde_json::to_value(example).unwrap(), + json!({ + "summary": "Serialized query", + "dataValue": { + "flag": true + }, + "serializedValue": "flag=true" + }) + ); + } + + #[test] + fn openapi_32_query_and_additional_operations_serialize() { + let path_item = PathItemBuilder::new() + .query(Some( + OperationBuilder::new() + .operation_id(Some("searchProducts")) + .request_body(Some( + request_body::RequestBodyBuilder::new() + .content( + "application/json", + ContentBuilder::new() + .schema(Some(Ref::from_schema_name("SearchCriteria"))) + .build(), + ) + .build(), + )) + .response("200", Response::new("Search results")), + )) + .additional_operation( + "COPY", + OperationBuilder::new() + .operation_id(Some("copyPet")) + .response("200", Response::new("Copied")), + ) + .build(); + + assert_eq!( + serde_json::to_value(path_item).unwrap(), + json!({ + "query": { + "operationId": "searchProducts", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SearchCriteria" + } + } + } + }, + "responses": { + "200": { + "description": "Search results" + } + } + }, + "additionalOperations": { + "COPY": { + "operationId": "copyPet", + "responses": { + "200": { + "description": "Copied" + } + } + } + } + }) + ); + } + + #[test] + fn openapi_32_querystring_parameter_and_cookie_style_serialize() { + let querystring = ParameterBuilder::from(Parameter::new("advancedQuery")) + .parameter_in(ParameterIn::QueryString) + .required(Required::False) + .content( + "application/x-www-form-urlencoded", + ContentBuilder::new() + .schema(Some( + ObjectBuilder::new() + .schema_type(Type::Object) + .property("foo", ObjectBuilder::new().schema_type(Type::String)) + .property("bar", ObjectBuilder::new().schema_type(Type::Boolean)), + )) + .examples_from_iter([( + "spacesAndPluses", + ExampleBuilder::new() + .description("Form-encoded query string") + .data_value(Some(json!({ + "foo": "a + b", + "bar": true + }))) + .serialized_value(Some("foo=a+%2B+b&bar=true")), + )]) + .build(), + ) + .build(); + let cookie = ParameterBuilder::from(Parameter::new("greeting")) + .parameter_in(ParameterIn::Cookie) + .style(Some(ParameterStyle::Cookie)) + .example(Some(json!("Hello, world!"))) + .build(); + + assert_eq!( + serde_json::to_value(querystring).unwrap(), + json!({ + "name": "advancedQuery", + "in": "querystring", + "required": false, + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "bar": { + "type": "boolean" + }, + "foo": { + "type": "string" + } + } + }, + "examples": { + "spacesAndPluses": { + "description": "Form-encoded query string", + "dataValue": { + "foo": "a + b", + "bar": true + }, + "serializedValue": "foo=a+%2B+b&bar=true" + } + } + } + } + }) + ); + assert_eq!( + serde_json::to_value(cookie).unwrap(), + json!({ + "name": "greeting", + "in": "cookie", + "required": true, + "style": "cookie", + "example": "Hello, world!" + }) + ); + } + + #[test] + fn openapi_32_components_media_types_streaming_and_response_summary_serialize() { + let event_payload = ObjectBuilder::new() + .schema_type(Type::Object) + .property("pet_id", ObjectBuilder::new().schema_type(Type::Integer)) + .property("status", ObjectBuilder::new().schema_type(Type::String)); + let server_event = ObjectBuilder::new() + .schema_type(Type::Object) + .property("event", ObjectBuilder::new().schema_type(Type::String)) + .property( + "data", + ObjectBuilder::new() + .schema_type(Type::String) + .content_media_type("application/json") + .content_schema(Some(Ref::from_schema_name("PetEventPayload"))), + ) + .property("id", ObjectBuilder::new().schema_type(Type::String)) + .property("retry", ObjectBuilder::new().schema_type(Type::Integer)); + let components = ComponentsBuilder::new() + .schema("PetEventPayload", event_payload) + .schema("ServerEvent", server_event) + .media_type( + "ServerSentEvents", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("ServerEvent"))) + .build(), + ) + .media_type( + "JsonLines", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("PetEventPayload"))) + .build(), + ) + .media_type( + "JsonTextSequences", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("PetEventPayload"))) + .build(), + ) + .media_type( + "MultipartMixed", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("PetEventPayload"))) + .build(), + ) + .build(); + let response = ResponseBuilder::new() + .summary(Some("Streaming response")) + .content( + "text/event-stream", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("ServerEvent"))) + .build(), + ) + .content( + "application/jsonl", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("PetEventPayload"))) + .build(), + ) + .content( + "application/json-seq", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("PetEventPayload"))) + .build(), + ) + .content( + "multipart/mixed", + ContentBuilder::new() + .item_schema(Some(Ref::from_schema_name("PetEventPayload"))) + .build(), + ) + .build(); + + assert_eq!( + serde_json::to_value(components).unwrap(), + json!({ + "schemas": { + "PetEventPayload": { + "type": "object", + "properties": { + "pet_id": { + "type": "integer" + }, + "status": { + "type": "string" + } + } + }, + "ServerEvent": { + "type": "object", + "properties": { + "data": { + "type": "string", + "contentMediaType": "application/json", + "contentSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "event": { + "type": "string" + }, + "id": { + "type": "string" + }, + "retry": { + "type": "integer" + } + } + } + }, + "mediaTypes": { + "JsonLines": { + "itemSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "JsonTextSequences": { + "itemSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "MultipartMixed": { + "itemSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "ServerSentEvents": { + "itemSchema": { + "$ref": "#/components/schemas/ServerEvent" + } + } + } + }) + ); + assert_eq!( + serde_json::to_value(response).unwrap(), + json!({ + "summary": "Streaming response", + "content": { + "application/json-seq": { + "itemSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "application/jsonl": { + "itemSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "multipart/mixed": { + "itemSchema": { + "$ref": "#/components/schemas/PetEventPayload" + } + }, + "text/event-stream": { + "itemSchema": { + "$ref": "#/components/schemas/ServerEvent" + } + } + } + }) + ); + } + + #[test] + fn openapi_32_oauth_device_authorization_and_deprecated_security_serialize() { + let oauth = SecurityScheme::OAuth2( + OAuth2::new([Flow::DeviceAuthorization(DeviceAuthorization::new( + "https://example.com/device", + "https://example.com/token", + Scopes::from_iter([("read:pets", "read pets")]), + ))]) + .with_metadata_url("https://example.com/.well-known/oauth-authorization-server") + .deprecated(Some(Deprecated::True)), + ); + + assert_eq!( + serde_json::to_value(oauth).unwrap(), + json!({ + "type": "oauth2", + "flows": { + "deviceAuthorization": { + "deviceAuthorizationUrl": "https://example.com/device", + "tokenUrl": "https://example.com/token", + "scopes": { + "read:pets": "read pets" + } + } + }, + "oauth2MetadataUrl": "https://example.com/.well-known/oauth-authorization-server", + "deprecated": true + }) + ); + } + #[test] fn serialize_openapi_json_minimal_success() { let openapi = OpenApi::new( diff --git a/utoipa/src/openapi/content.rs b/utoipa/src/openapi/content.rs index f40bd48f9..d5e478f5b 100644 --- a/utoipa/src/openapi/content.rs +++ b/utoipa/src/openapi/content.rs @@ -22,11 +22,20 @@ builder! { #[derive(Serialize, Deserialize, Default, Clone, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[non_exhaustive] + #[serde(rename_all = "camelCase")] pub struct Content { /// Schema used in response body or request body. #[serde(skip_serializing_if = "Option::is_none")] pub schema: Option>, + /// Schema used for each item in a streaming or event-based media type. + #[serde(skip_serializing_if = "Option::is_none")] + pub item_schema: Option>, + + /// Description of this media type. Markdown syntax is supported. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Example for request body or response body. #[serde(skip_serializing_if = "Option::is_none")] pub example: Option, @@ -49,6 +58,14 @@ builder! { #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] pub encoding: BTreeMap, + /// Encoding information for tuple-like sequential or array items. + #[serde(skip_serializing_if = "Vec::is_empty", default)] + pub prefix_encoding: Vec, + + /// Encoding information for each item in a sequential or array media type. + #[serde(skip_serializing_if = "Option::is_none")] + pub item_encoding: Option>, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -71,6 +88,16 @@ impl ContentBuilder { set_value!(self schema schema.map(|schema| schema.into())) } + /// Add item schema for a streaming or event-based media type. + pub fn item_schema>>(mut self, item_schema: Option) -> Self { + set_value!(self item_schema item_schema.map(|schema| schema.into())) + } + + /// Add or change description of this media type. + pub fn description>(mut self, description: Option) -> Self { + set_value!(self description description.map(Into::into)) + } + /// Add example of schema. pub fn example(mut self, example: Option) -> Self { set_value!(self example example) @@ -117,8 +144,33 @@ impl ContentBuilder { self } + /// Add encoding information for tuple-like sequential or array items. + pub fn prefix_encoding, E: Into>( + mut self, + prefix_encoding: I, + ) -> Self { + set_value!(self prefix_encoding prefix_encoding.into_iter().map(Into::into).collect()) + } + + /// Add encoding information for each item in a sequential or array media type. + pub fn item_encoding>(mut self, item_encoding: Option) -> Self { + set_value!(self item_encoding item_encoding.map(|encoding| Box::new(encoding.into()))) + } + /// Add openapi extensions (x-something) of the API. pub fn extensions(mut self, extensions: Option) -> Self { set_value!(self extensions extensions) } } + +impl From for RefOr { + fn from(content_builder: ContentBuilder) -> Self { + Self::T(content_builder.build()) + } +} + +impl From for RefOr { + fn from(r: super::Ref) -> Self { + Self::Ref(r) + } +} diff --git a/utoipa/src/openapi/encoding.rs b/utoipa/src/openapi/encoding.rs index d63a5a041..28bb19096 100644 --- a/utoipa/src/openapi/encoding.rs +++ b/utoipa/src/openapi/encoding.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use super::extensions::Extensions; -use super::{builder, path::ParameterStyle, set_value, Header}; +use super::{builder, path::ParameterStyle, set_value, Header, Ref, RefOr}; builder! { EncodingBuilder; @@ -29,7 +29,7 @@ builder! { /// Content-Disposition. Content-Type is described separately and SHALL be ignored in this /// section. This property SHALL be ignored if the request body media type is not a multipart. #[serde(skip_serializing_if = "BTreeMap::is_empty")] - pub headers: BTreeMap, + pub headers: BTreeMap>, /// Describes how a specific property value will be serialized depending on its type. See /// Parameter Object for details on the style property. The behavior follows the same values as @@ -53,6 +53,18 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub allow_reserved: Option, + /// Encoding information for nested object properties. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub encoding: BTreeMap, + + /// Encoding information for tuple-like nested array items. + #[serde(skip_serializing_if = "Vec::is_empty", default)] + pub prefix_encoding: Vec, + + /// Encoding information for each nested array item. + #[serde(skip_serializing_if = "Option::is_none")] + pub item_encoding: Option>, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -67,7 +79,15 @@ impl EncodingBuilder { /// Add a [`Header`]. See [`Encoding::headers`]. pub fn header, H: Into

>(mut self, header_name: S, header: H) -> Self { - self.headers.insert(header_name.into(), header.into()); + self.headers + .insert(header_name.into(), header.into().into()); + + self + } + + /// Add a [`Header`] reference. See [`Encoding::headers`]. + pub fn header_ref>(mut self, header_name: S, header: Ref) -> Self { + self.headers.insert(header_name.into(), RefOr::Ref(header)); self } @@ -87,6 +107,29 @@ impl EncodingBuilder { set_value!(self allow_reserved allow_reserved) } + /// Add nested encoding information for an object property. + pub fn encoding, E: Into>( + mut self, + property_name: S, + encoding: E, + ) -> Self { + self.encoding.insert(property_name.into(), encoding.into()); + self + } + + /// Add nested encoding information for tuple-like array items. + pub fn prefix_encoding, E: Into>( + mut self, + prefix_encoding: I, + ) -> Self { + set_value!(self prefix_encoding prefix_encoding.into_iter().map(Into::into).collect()) + } + + /// Add nested encoding information for each array item. + pub fn item_encoding>(mut self, item_encoding: Option) -> Self { + set_value!(self item_encoding item_encoding.map(|encoding| Box::new(encoding.into()))) + } + /// Add openapi extensions (x-something) of the API. pub fn extensions(mut self, extensions: Option) -> Self { set_value!(self extensions extensions) diff --git a/utoipa/src/openapi/example.rs b/utoipa/src/openapi/example.rs index b233aa560..989a0a6a8 100644 --- a/utoipa/src/openapi/example.rs +++ b/utoipa/src/openapi/example.rs @@ -45,6 +45,14 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub value: Option, + /// Embedded example value in the same form as data validated by a schema. + #[serde(skip_serializing_if = "Option::is_none")] + pub data_value: Option, + + /// String representation of the example value after serialization. + #[serde(skip_serializing_if = "Option::is_none")] + pub serialized_value: Option, + /// An URI that points to a literal example value. [`Example::external_value`] provides the /// capability to references an example that cannot be easily included in JSON or YAML. /// [`Example::value`] and [`Example::external_value`] are mutually exclusive. @@ -83,6 +91,20 @@ impl ExampleBuilder { set_value!(self value value) } + /// Add or change embedded data value for the [`Example`]. + pub fn data_value(mut self, data_value: Option) -> Self { + set_value!(self data_value data_value) + } + + /// Add or change serialized value for the [`Example`]. + pub fn serialized_value>(mut self, serialized_value: Option) -> Self { + set_value!( + self + serialized_value + serialized_value.map(|serialized_value| serialized_value.into()) + ) + } + /// Add or change an URI that points to a literal example value. [`Example::external_value`] /// provides the capability to references an example that cannot be easily included /// in JSON or YAML. [`Example::value`] and [`Example::external_value`] are mutually exclusive. diff --git a/utoipa/src/openapi/header.rs b/utoipa/src/openapi/header.rs index 7417eb8d2..395a16b25 100644 --- a/utoipa/src/openapi/header.rs +++ b/utoipa/src/openapi/header.rs @@ -51,7 +51,7 @@ builder! { /// A map containing the representations for the header. #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] - pub content: BTreeMap, + pub content: BTreeMap>, /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] @@ -103,8 +103,18 @@ impl Default for Header { impl HeaderBuilder { /// Add schema of header. - pub fn schema>>(mut self, component: I) -> Self { - set_value!(self schema Some(component.into())) + pub fn schema>>(mut self, component: Option) -> Self { + set_value!(self schema component.map(Into::into)) + } + + /// Add media type representation for the header. + pub fn content, C: Into>>( + mut self, + content_type: S, + content: C, + ) -> Self { + self.content.insert(content_type.into(), content.into()); + self } /// Add additional description for header. @@ -151,7 +161,11 @@ impl HeaderBuilder { } /// Add media type content representation to [`Header`]. - pub fn content_from_iter, N: Into, V: Into>( + pub fn content_from_iter< + E: IntoIterator, + N: Into, + V: Into>, + >( mut self, content: E, ) -> Self { @@ -211,7 +225,7 @@ mod tests { let header = Header { schema: None, - content: BTreeMap::from_iter([("application/json".to_string(), content)]), + content: BTreeMap::from_iter([("application/json".to_string(), content.into())]), examples: BTreeMap::from_iter([("test_example".to_string(), example.into())]), ..Default::default() }; diff --git a/utoipa/src/openapi/link.rs b/utoipa/src/openapi/link.rs index 365d157c6..9a53da556 100644 --- a/utoipa/src/openapi/link.rs +++ b/utoipa/src/openapi/link.rs @@ -26,6 +26,7 @@ builder! { #[derive(Serialize, Deserialize, Clone, PartialEq, Default)] #[cfg_attr(feature = "debug", derive(Debug))] #[non_exhaustive] + #[serde(rename_all = "camelCase")] pub struct Link { /// A relative or absolute URI reference to an OAS operation. This field is /// mutually exclusive of the _`operation_id`_ field, and **must** point to an [Operation diff --git a/utoipa/src/openapi/path.rs b/utoipa/src/openapi/path.rs index 79bac8af1..dabbfab61 100644 --- a/utoipa/src/openapi/path.rs +++ b/utoipa/src/openapi/path.rs @@ -4,14 +4,16 @@ use crate::Path; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::collections::BTreeMap; use super::{ builder, + content::Content, extensions::Extensions, request_body::RequestBody, response::{Response, Responses}, security::SecurityRequirement, - set_value, Deprecated, ExternalDocs, RefOr, Required, Schema, Server, + set_value, Deprecated, ExternalDocs, Ref, RefOr, Required, Schema, Server, }; #[cfg(not(feature = "preserve_path_order"))] @@ -23,6 +25,9 @@ pub type PathsMap = std::collections::BTreeMap; #[doc(hidden)] pub type PathsMap = indexmap::IndexMap; +/// OpenAPI Callback Object mapping callback expressions to path items. +pub type Callback = BTreeMap>; + builder! { PathsBuilder; @@ -230,6 +235,10 @@ builder! { #[cfg_attr(feature = "debug", derive(Debug))] #[serde(rename_all = "camelCase")] pub struct PathItem { + /// Allows referencing another Path Item Object. + #[serde(rename = "$ref", skip_serializing_if = "Option::is_none")] + pub ref_path: Option, + /// Optional summary intended to apply all operations in this [`PathItem`]. #[serde(skip_serializing_if = "Option::is_none")] pub summary: Option, @@ -248,7 +257,7 @@ builder! { /// contain duplicate parameters. They can be overridden in [`Operation`] level but cannot be /// removed there. #[serde(skip_serializing_if = "Option::is_none")] - pub parameters: Option>, + pub parameters: Option>>, /// Get [`Operation`] for the [`PathItem`]. #[serde(skip_serializing_if = "Option::is_none")] @@ -282,6 +291,14 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub trace: Option, + /// Query [`Operation`] for the [`PathItem`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub query: Option, + + /// Operation used for HTTP methods or other operations not explicitly listed on this path. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub additional_operations: BTreeMap, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -356,10 +373,23 @@ impl PathItem { if path_item.trace.is_some() && self.trace.is_none() { self.trace = path_item.trace; } + if path_item.query.is_some() && self.query.is_none() { + self.query = path_item.query; + } + for (method, operation) in path_item.additional_operations { + self.additional_operations + .entry(method) + .or_insert(operation); + } } } impl PathItemBuilder { + /// Add or change reference to another Path Item Object. + pub fn ref_path>(mut self, ref_path: Option) -> Self { + set_value!(self ref_path ref_path.map(Into::into)) + } + /// Append a new [`Operation`] by [`HttpMethod`] to this [`PathItem`]. Operations can /// hold only one operation per [`HttpMethod`]. pub fn operation>(mut self, http_method: HttpMethod, operation: O) -> Self { @@ -377,6 +407,42 @@ impl PathItemBuilder { self } + /// Add or change query [`Operation`] for this [`PathItem`]. + pub fn query>(mut self, operation: Option) -> Self { + set_value!(self query operation.map(Into::into)) + } + + /// Add or change operation used for HTTP methods or other operations not explicitly listed on + /// this path. + pub fn additional_operations< + I: IntoIterator, + S: Into, + O: Into, + >( + mut self, + additional_operations: I, + ) -> Self { + self.additional_operations.extend( + additional_operations + .into_iter() + .map(|(method, operation)| (method.into(), operation.into())), + ); + + self + } + + /// Add operation used for an HTTP method not explicitly listed on this path. + pub fn additional_operation, O: Into>( + mut self, + method: S, + operation: O, + ) -> Self { + self.additional_operations + .insert(method.into(), operation.into()); + + self + } + /// Add or change summary intended to apply all operations in this [`PathItem`]. pub fn summary>(mut self, summary: Option) -> Self { set_value!(self summary summary.map(|summary| summary.into())) @@ -396,7 +462,12 @@ impl PathItemBuilder { /// Append list of [`Parameter`]s common to all [`Operation`]s to this [`PathItem`]. pub fn parameters>(mut self, parameters: Option) -> Self { - set_value!(self parameters parameters.map(|parameters| parameters.into_iter().collect())) + set_value!(self parameters parameters.map(|parameters| parameters.into_iter().map(Into::into).collect())) + } + + /// Append list of parameter references common to all [`Operation`]s to this [`PathItem`]. + pub fn parameter_refs>(mut self, refs: Option) -> Self { + set_value!(self parameters refs.map(|refs| refs.into_iter().map(RefOr::Ref).collect())) } /// Add openapi extensions (x-something) to this [`PathItem`]. @@ -486,19 +557,18 @@ builder! { /// List of applicable parameters for this [`Operation`]. #[serde(skip_serializing_if = "Option::is_none")] - pub parameters: Option>, + pub parameters: Option>>, /// Optional request body for this [`Operation`]. #[serde(skip_serializing_if = "Option::is_none")] - pub request_body: Option, + pub request_body: Option>, /// List of possible responses returned by the [`Operation`]. pub responses: Responses, - // TODO - #[allow(missing_docs)] - #[serde(skip_serializing_if = "Option::is_none")] - pub callbacks: Option, + /// Map of callbacks related to this operation. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub callbacks: BTreeMap>, /// Define whether the operation is deprecated or not and thus should be avoided consuming. #[serde(skip_serializing_if = "Option::is_none")] @@ -570,12 +640,16 @@ impl OperationBuilder { ) -> Self { self.parameters = parameters.map(|parameters| { if let Some(mut params) = self.parameters { - params.extend(parameters.into_iter().map(|parameter| parameter.into())); + params.extend( + parameters + .into_iter() + .map(|parameter| RefOr::T(parameter.into())), + ); params } else { parameters .into_iter() - .map(|parameter| parameter.into()) + .map(|parameter| RefOr::T(parameter.into())) .collect() } }); @@ -586,9 +660,21 @@ impl OperationBuilder { /// Append parameter to [`Operation`] parameters. pub fn parameter>(mut self, parameter: P) -> Self { match self.parameters { - Some(ref mut parameters) => parameters.push(parameter.into()), + Some(ref mut parameters) => parameters.push(RefOr::T(parameter.into())), + None => { + self.parameters = Some(vec![RefOr::T(parameter.into())]); + } + } + + self + } + + /// Append parameter reference to [`Operation`] parameters. + pub fn parameter_ref(mut self, parameter: Ref) -> Self { + match self.parameters { + Some(ref mut parameters) => parameters.push(RefOr::Ref(parameter)), None => { - self.parameters = Some(vec![parameter.into()]); + self.parameters = Some(vec![RefOr::Ref(parameter)]); } } @@ -597,7 +683,12 @@ impl OperationBuilder { /// Add or change request body of the [`Operation`]. pub fn request_body(mut self, request_body: Option) -> Self { - set_value!(self request_body request_body) + set_value!(self request_body request_body.map(Into::into)) + } + + /// Add or change request body reference of the [`Operation`]. + pub fn request_body_ref(mut self, request_body: Option) -> Self { + set_value!(self request_body request_body.map(RefOr::Ref)) } /// Add or change responses of the [`Operation`]. @@ -621,6 +712,33 @@ impl OperationBuilder { self } + /// Add a callback to this [`Operation`]. + pub fn callback, C: Into>>( + mut self, + name: S, + callback: C, + ) -> Self { + self.callbacks.insert(name.into(), callback.into()); + self + } + + /// Add callbacks to this [`Operation`] from an iterator. + pub fn callbacks_from_iter< + I: IntoIterator, + S: Into, + C: Into>, + >( + mut self, + callbacks: I, + ) -> Self { + self.callbacks.extend( + callbacks + .into_iter() + .map(|(name, callback)| (name.into(), callback.into())), + ); + self + } + /// Add or change deprecated status of the [`Operation`]. pub fn deprecated(mut self, deprecated: Option) -> Self { set_value!(self deprecated deprecated) @@ -667,6 +785,18 @@ impl OperationBuilder { } } +impl From for RefOr { + fn from(r: Ref) -> Self { + Self::Ref(r) + } +} + +impl From for RefOr { + fn from(r: Ref) -> Self { + Self::Ref(r) + } +} + builder! { ParameterBuilder; @@ -705,6 +835,10 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub schema: Option>, + /// Map of media type representations for the parameter. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub content: BTreeMap>, + /// Describes how [`Parameter`] is being serialized depending on [`Parameter::schema`] (type of a content). /// Default value is based on [`ParameterIn`]. #[serde(skip_serializing_if = "Option::is_none")] @@ -791,6 +925,33 @@ impl ParameterBuilder { set_value!(self schema component.map(|component| component.into())) } + /// Add media type representation for the [`Parameter`]. + pub fn content, C: Into>>( + mut self, + content_type: S, + content: C, + ) -> Self { + self.content.insert(content_type.into(), content.into()); + self + } + + /// Add media type representations from an iterator. + pub fn contents_from_iter< + I: IntoIterator, + S: Into, + C: Into>, + >( + mut self, + content: I, + ) -> Self { + self.content.extend( + content + .into_iter() + .map(|(content_type, content)| (content_type.into(), content.into())), + ); + self + } + /// Add or change serialization style of [`Parameter`]. pub fn style(mut self, style: Option) -> Self { set_value!(self style style) @@ -830,6 +991,9 @@ pub enum ParameterIn { Header, /// Declares that parameter is used as cookie value. Cookie, + /// Declares that parameter represents the entire query string. + #[serde(rename = "querystring")] + QueryString, } impl Default for ParameterIn { @@ -867,6 +1031,8 @@ pub enum ParameterStyle { /// Simple way of rendering nested objects using form parameters .e.g. _`color[B]=150`_. /// Allowed with [`ParameterIn::Query`]. DeepObject, + /// Cookie parameter serialization style. + Cookie, } #[cfg(test)] @@ -982,7 +1148,7 @@ mod tests { assert!(operation.parameters.is_none()); assert!(operation.request_body.is_none()); assert!(operation.responses.responses.is_empty()); - assert!(operation.callbacks.is_none()); + assert!(operation.callbacks.is_empty()); assert!(operation.deprecated.is_none()); assert!(operation.security.is_none()); assert!(operation.servers.is_none()); diff --git a/utoipa/src/openapi/request_body.rs b/utoipa/src/openapi/request_body.rs index 6f21de638..ff148e0dd 100644 --- a/utoipa/src/openapi/request_body.rs +++ b/utoipa/src/openapi/request_body.rs @@ -6,7 +6,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use super::extensions::Extensions; -use super::{builder, set_value, Content, Required}; +use super::{builder, set_value, Content, RefOr, Required}; builder! { RequestBodyBuilder; @@ -24,7 +24,7 @@ builder! { pub description: Option, /// Map of request body contents mapped by content type e.g. `application/json`. - pub content: BTreeMap, + pub content: BTreeMap>, /// Determines whether request body is required in the request or not. #[serde(skip_serializing_if = "Option::is_none")] @@ -55,8 +55,25 @@ impl RequestBodyBuilder { } /// Add [`Content`] by content type e.g `application/json` to [`RequestBody`]. - pub fn content>(mut self, content_type: S, content: Content) -> Self { - self.content.insert(content_type.into(), content); + pub fn content, C: Into>( + mut self, + content_type: S, + content: C, + ) -> Self { + self.content + .insert(content_type.into(), content.into().into()); + + self + } + + /// Add reusable [`Content`] reference by content type e.g `application/json`. + pub fn content_ref>( + mut self, + content_type: S, + content_ref: super::Ref, + ) -> Self { + self.content + .insert(content_type.into(), RefOr::Ref(content_ref)); self } @@ -108,7 +125,8 @@ impl RequestBodyExt for RequestBody { fn json_schema_ref(mut self, ref_name: &str) -> RequestBody { self.content.insert( "application/json".to_string(), - crate::openapi::Content::new(Some(crate::openapi::Ref::from_schema_name(ref_name))), + crate::openapi::Content::new(Some(crate::openapi::Ref::from_schema_name(ref_name))) + .into(), ); self } diff --git a/utoipa/src/openapi/response.rs b/utoipa/src/openapi/response.rs index 62239b37d..918f3fb5a 100644 --- a/utoipa/src/openapi/response.rs +++ b/utoipa/src/openapi/response.rs @@ -118,19 +118,24 @@ builder! { #[cfg_attr(feature = "debug", derive(Debug))] #[serde(rename_all = "camelCase")] pub struct Response { + /// Short summary of the response. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, + /// Description of the response. Response support markdown syntax. + #[serde(skip_serializing_if = "String::is_empty", default)] pub description: String, /// Map of headers identified by their name. `Content-Type` header will be ignored. #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] - pub headers: BTreeMap, + pub headers: BTreeMap>, /// Map of response [`Content`] objects identified by response body content type e.g `application/json`. /// /// [`Content`]s are stored within [`IndexMap`] to retain their insertion order. Swagger UI /// will create and show default example according to the first entry in `content` map. #[serde(skip_serializing_if = "IndexMap::is_empty", default)] - pub content: IndexMap, + pub content: IndexMap>, /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] @@ -161,16 +166,41 @@ impl ResponseBuilder { set_value!(self description description.into()) } + /// Add short summary of the response. + pub fn summary>(mut self, summary: Option) -> Self { + set_value!(self summary summary.map(Into::into)) + } + /// Add [`Content`] of the [`Response`] with content type e.g `application/json`. - pub fn content>(mut self, content_type: S, content: Content) -> Self { - self.content.insert(content_type.into(), content); + pub fn content, C: Into>( + mut self, + content_type: S, + content: C, + ) -> Self { + self.content + .insert(content_type.into(), content.into().into()); + + self + } + + /// Add reusable [`Content`] reference by content type e.g `application/json`. + pub fn content_ref>(mut self, content_type: S, content_ref: Ref) -> Self { + self.content + .insert(content_type.into(), RefOr::Ref(content_ref)); self } /// Add response [`Header`]. pub fn header>(mut self, name: S, header: Header) -> Self { - self.headers.insert(name.into(), header); + self.headers.insert(name.into(), header.into()); + + self + } + + /// Add response [`Header`] reference. + pub fn header_ref>(mut self, name: S, header: Ref) -> Self { + self.headers.insert(name.into(), RefOr::Ref(header)); self } @@ -244,7 +274,7 @@ impl ResponseExt for Response { fn json_schema_ref(mut self, ref_name: &str) -> Response { self.content.insert( "application/json".to_string(), - Content::new(Some(crate::openapi::Ref::from_schema_name(ref_name))), + Content::new(Some(crate::openapi::Ref::from_schema_name(ref_name))).into(), ); self } diff --git a/utoipa/src/openapi/schema.rs b/utoipa/src/openapi/schema.rs index 81e36df70..7c491b3f6 100644 --- a/utoipa/src/openapi/schema.rs +++ b/utoipa/src/openapi/schema.rs @@ -9,7 +9,18 @@ use serde_json::Value; use super::extensions::Extensions; use super::RefOr; -use super::{builder, security::SecurityScheme, set_value, xml::Xml, Deprecated, Response}; +use super::{ + builder, + example::Example, + header::Header, + link::Link, + path::{Callback, Parameter, PathItem}, + request_body::RequestBody, + security::SecurityScheme, + set_value, + xml::Xml, + Content, Deprecated, Response, +}; use crate::{ToResponse, ToSchema}; macro_rules! component_from_builder { @@ -73,11 +84,45 @@ builder! { #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] pub responses: BTreeMap>, + /// Map of reusable parameters. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub parameters: BTreeMap>, + + /// Map of reusable examples. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub examples: BTreeMap>, + + /// Map of reusable request bodies. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub request_bodies: BTreeMap>, + + /// Map of reusable headers. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub headers: BTreeMap>, + + /// Map of reusable links. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub links: BTreeMap>, + + /// Map of reusable callbacks. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub callbacks: BTreeMap>, + + /// Map of reusable path items. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub path_items: BTreeMap, + + /// Map of reusable [OpenAPI Media Type Object][media_type]s. + /// + /// [media_type]: https://spec.openapis.org/oas/latest.html#media-type-object + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub media_types: BTreeMap>, + /// Map of reusable [OpenAPI Security Scheme Object][security_scheme]s. /// /// [security_scheme]: https://spec.openapis.org/oas/latest.html#security-scheme-object #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] - pub security_schemes: BTreeMap, + pub security_schemes: BTreeMap>, /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] @@ -98,7 +143,7 @@ impl Components { /// referenced by [`SecurityRequirement`][requirement]s. Second parameter is the [`SecurityScheme`]. /// /// [requirement]: ../security/struct.SecurityRequirement.html - pub fn add_security_scheme, S: Into>( + pub fn add_security_scheme, S: Into>>( &mut self, name: N, security_scheme: S, @@ -116,7 +161,7 @@ impl Components { pub fn add_security_schemes_from_iter< I: IntoIterator, N: Into, - S: Into, + S: Into>, >( &mut self, schemas: I, @@ -221,6 +266,229 @@ impl ComponentsBuilder { self.response(name, response) } + /// Add [`Content`] to [`Components`] as a reusable media type object. + /// + /// Reusable media types are an OpenAPI 3.2 addition, added to the `mediaTypes` map of + /// [`Components`]. They can then be referenced by name from `content` maps using + /// [`RefOr::Ref`], instead of repeating the same media type definition across multiple + /// operations. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, ContentBuilder, ObjectBuilder, Type}; + /// let components = ComponentsBuilder::new() + /// .media_type( + /// "PetJson", + /// ContentBuilder::new() + /// .schema(Some(ObjectBuilder::new().schema_type(Type::Object))) + /// .build(), + /// ) + /// .build(); + /// ``` + pub fn media_type, C: Into>>( + mut self, + name: S, + media_type: C, + ) -> Self { + self.media_types.insert(name.into(), media_type.into()); + self + } + + /// Add multiple reusable media type objects from an iterator. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, ContentBuilder, ObjectBuilder, Type}; + /// let components = ComponentsBuilder::new() + /// .media_types_from_iter([ + /// ( + /// "PetJson", + /// ContentBuilder::new() + /// .schema(Some(ObjectBuilder::new().schema_type(Type::Object))) + /// .build(), + /// ), + /// ]) + /// .build(); + /// ``` + pub fn media_types_from_iter< + I: IntoIterator, + S: Into, + C: Into>, + >( + mut self, + media_types: I, + ) -> Self { + self.media_types.extend( + media_types + .into_iter() + .map(|(name, media_type)| (name.into(), media_type.into())), + ); + + self + } + + /// Add reusable [`Parameter`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, path::{ParameterBuilder, ParameterIn}, ObjectBuilder, Type}; + /// let components = ComponentsBuilder::new() + /// .parameter( + /// "Limit", + /// ParameterBuilder::new() + /// .name("limit") + /// .parameter_in(ParameterIn::Query) + /// .schema(Some(ObjectBuilder::new().schema_type(Type::Integer))) + /// .build(), + /// ) + /// .build(); + /// ``` + pub fn parameter, P: Into>>( + mut self, + name: S, + parameter: P, + ) -> Self { + self.parameters.insert(name.into(), parameter.into()); + self + } + + /// Add reusable [`Example`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, example::ExampleBuilder}; + /// let components = ComponentsBuilder::new() + /// .example("Accepted", ExampleBuilder::new().summary("Accepted").build()) + /// .build(); + /// ``` + pub fn example, E: Into>>( + mut self, + name: S, + example: E, + ) -> Self { + self.examples.insert(name.into(), example.into()); + self + } + + /// Add reusable [`RequestBody`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, request_body::RequestBodyBuilder, ContentBuilder, Ref}; + /// let components = ComponentsBuilder::new() + /// .request_body( + /// "EventRequest", + /// RequestBodyBuilder::new() + /// .content( + /// "application/json", + /// ContentBuilder::new() + /// .schema(Some(Ref::from_schema_name("EventPayload"))) + /// .build(), + /// ) + /// .build(), + /// ) + /// .build(); + /// ``` + pub fn request_body, R: Into>>( + mut self, + name: S, + request_body: R, + ) -> Self { + self.request_bodies.insert(name.into(), request_body.into()); + self + } + + /// Add reusable [`Header`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, header::HeaderBuilder, ObjectBuilder, Type}; + /// let components = ComponentsBuilder::new() + /// .header( + /// "RateLimit", + /// HeaderBuilder::new() + /// .schema(Some(ObjectBuilder::new().schema_type(Type::Integer))) + /// .build(), + /// ) + /// .build(); + /// ``` + pub fn header, H: Into>>(mut self, name: S, header: H) -> Self { + self.headers.insert(name.into(), header.into()); + self + } + + /// Add reusable [`Link`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, link::LinkBuilder}; + /// let components = ComponentsBuilder::new() + /// .link("GetEvent", LinkBuilder::new().operation_id("getEvent").build()) + /// .build(); + /// ``` + pub fn link, L: Into>>(mut self, name: S, link: L) -> Self { + self.links.insert(name.into(), link.into()); + self + } + + /// Add reusable [`Callback`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, path::{PathItemBuilder, OperationBuilder}, response::ResponseBuilder}; + /// # use std::collections::BTreeMap; + /// let callback_path = PathItemBuilder::new() + /// .query(Some( + /// OperationBuilder::new().response("200", ResponseBuilder::new()), + /// )) + /// .build(); + /// let components = ComponentsBuilder::new() + /// .callback( + /// "EventCallback", + /// BTreeMap::from([( + /// "{$request.body#/callbackUrl}".to_string(), + /// callback_path.into(), + /// )]), + /// ) + /// .build(); + /// ``` + pub fn callback, C: Into>>( + mut self, + name: S, + callback: C, + ) -> Self { + self.callbacks.insert(name.into(), callback.into()); + self + } + + /// Add reusable [`PathItem`] to [`Components`]. + /// + /// # Examples + /// + /// ```rust + /// # use utoipa::openapi::{ComponentsBuilder, path::{PathItemBuilder, OperationBuilder}, response::ResponseBuilder}; + /// let path_item = PathItemBuilder::new() + /// .query(Some( + /// OperationBuilder::new().response("200", ResponseBuilder::new()), + /// )) + /// .build(); + /// let components = ComponentsBuilder::new() + /// .path_item("EventPath", path_item) + /// .build(); + /// ``` + pub fn path_item, P: Into>(mut self, name: S, path_item: P) -> Self { + self.path_items.insert(name.into(), path_item.into()); + self + } + /// Add multiple [`struct@Response`]s to [`Components`] from iterator. /// /// Like the [`ComponentsBuilder::schemas_from_iter`] this allows adding multiple responses by @@ -248,7 +516,7 @@ impl ComponentsBuilder { /// referenced by [`SecurityRequirement`][requirement]s. Second parameter is the [`SecurityScheme`]. /// /// [requirement]: ../security/struct.SecurityRequirement.html - pub fn security_scheme, S: Into>( + pub fn security_scheme, S: Into>>( mut self, name: N, security_scheme: S, @@ -1087,6 +1355,10 @@ builder! { /// See more details at #[serde(skip_serializing_if = "String::is_empty", default)] pub content_media_type: String, + + /// The _`content_schema`_ keyword specifies the schema of string-encoded content. + #[serde(skip_serializing_if = "Option::is_none")] + pub content_schema: Option>>, } } @@ -1309,6 +1581,11 @@ impl ObjectBuilder { set_value!(self content_media_type content_media_type.into()) } + /// Set or change [`Object::content_schema`]. + pub fn content_schema>>(mut self, content_schema: Option) -> Self { + set_value!(self content_schema content_schema.map(|schema| Box::new(schema.into()))) + } + to_array_builder!(); } @@ -1736,6 +2013,10 @@ builder! { #[serde(skip_serializing_if = "String::is_empty", default)] pub content_media_type: String, + /// The _`content_schema`_ keyword specifies the schema of string-encoded content. + #[serde(skip_serializing_if = "Option::is_none")] + pub content_schema: Option>>, + /// Optional extensions `x-something`. #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -1761,6 +2042,7 @@ impl Default for Array { extensions: Default::default(), content_encoding: Default::default(), content_media_type: Default::default(), + content_schema: Default::default(), } } } @@ -1901,6 +2183,11 @@ impl ArrayBuilder { set_value!(self content_media_type content_media_type.into()) } + /// Set or change [`Array::content_schema`]. + pub fn content_schema>>(mut self, content_schema: Option) -> Self { + set_value!(self content_schema content_schema.map(|schema| Box::new(schema.into()))) + } + /// Add openapi extensions (`x-something`) for [`Array`]. pub fn extensions(mut self, extensions: Option) -> Self { set_value!(self extensions extensions) @@ -2093,18 +2380,22 @@ pub enum KnownFormat { /// 8 bit unsigned integer. #[cfg(feature = "non_strict_integers")] #[cfg_attr(doc_cfg, doc(cfg(feature = "non_strict_integers")))] + #[serde(rename = "uint8")] UInt8, /// 16 bit unsigned integer. #[cfg(feature = "non_strict_integers")] #[cfg_attr(doc_cfg, doc(cfg(feature = "non_strict_integers")))] + #[serde(rename = "uint16")] UInt16, /// 32 bit unsigned integer. #[cfg(feature = "non_strict_integers")] #[cfg_attr(doc_cfg, doc(cfg(feature = "non_strict_integers")))] + #[serde(rename = "uint32")] UInt32, /// 64 bit unsigned integer. #[cfg(feature = "non_strict_integers")] #[cfg_attr(doc_cfg, doc(cfg(feature = "non_strict_integers")))] + #[serde(rename = "uint64")] UInt64, /// floating point number. Float, @@ -2193,6 +2484,27 @@ mod tests { use super::*; use crate::openapi::*; + #[cfg(feature = "non_strict_integers")] + #[test] + fn serialize_unsigned_integer_known_formats() { + assert_eq!( + serde_json::to_value(KnownFormat::UInt8).unwrap(), + json!("uint8") + ); + assert_eq!( + serde_json::to_value(KnownFormat::UInt16).unwrap(), + json!("uint16") + ); + assert_eq!( + serde_json::to_value(KnownFormat::UInt32).unwrap(), + json!("uint32") + ); + assert_eq!( + serde_json::to_value(KnownFormat::UInt64).unwrap(), + json!("uint64") + ); + } + #[test] fn create_schema_serializes_json() -> Result<(), serde_json::Error> { let openapi = OpenApiBuilder::new() @@ -2486,6 +2798,7 @@ mod tests { "TLS", SecurityScheme::MutualTls { description: None, + deprecated: None, extensions: None, }, ) diff --git a/utoipa/src/openapi/security.rs b/utoipa/src/openapi/security.rs index 963ea98de..d01c54200 100644 --- a/utoipa/src/openapi/security.rs +++ b/utoipa/src/openapi/security.rs @@ -7,7 +7,7 @@ use std::{collections::BTreeMap, iter}; use serde::{Deserialize, Serialize}; -use super::{builder, extensions::Extensions}; +use super::{builder, extensions::Extensions, Deprecated}; /// OpenAPI [security requirement][security] object. /// @@ -180,11 +180,27 @@ pub enum SecurityScheme { /// Authentication is done via client side certificate. /// /// OpenApi 3.1 type + /// + /// # Examples + /// + /// Declare mutual TLS authentication with a description. + /// ```rust + /// # use utoipa::openapi::security::SecurityScheme; + /// SecurityScheme::MutualTls { + /// description: Some("Client certificate required".to_string()), + /// deprecated: None, + /// extensions: None, + /// }; + /// ``` #[serde(rename = "mutualTLS")] MutualTls { - #[allow(missing_docs)] + /// Optional description explaining how the mutual TLS certificate should be obtained + /// and used. Description supports markdown syntax. #[serde(skip_serializing_if = "Option::is_none")] description: Option, + /// Declares whether the security scheme is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + deprecated: Option, /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] extensions: Option, @@ -216,6 +232,10 @@ pub struct ApiKeyValue { #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Declares whether the security scheme is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + pub deprecated: Option, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -235,6 +255,7 @@ impl ApiKeyValue { Self { name: name.into(), description: None, + deprecated: None, extensions: Default::default(), } } @@ -252,9 +273,25 @@ impl ApiKeyValue { Self { name: name.into(), description: Some(description.into()), + deprecated: None, extensions: Default::default(), } } + + /// Add or change deprecated status. + /// + /// # Examples + /// + /// Mark an api key security scheme as deprecated. + /// ```rust + /// # use utoipa::openapi::security::ApiKeyValue; + /// # use utoipa::openapi::Deprecated; + /// ApiKeyValue::new("api_key").deprecated(Some(Deprecated::True)); + /// ``` + pub fn deprecated(mut self, deprecated: Option) -> Self { + self.deprecated = deprecated; + self + } } builder! { @@ -279,6 +316,10 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Declares whether the security scheme is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + pub deprecated: Option, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -302,6 +343,7 @@ impl Http { scheme, bearer_format: None, description: None, + deprecated: None, extensions: Default::default(), } } @@ -347,6 +389,25 @@ impl HttpBuilder { self } + + /// Add or change deprecated status. + /// + /// # Examples + /// + /// Mark a bearer HTTP authentication scheme as deprecated. + /// ```rust + /// # use utoipa::openapi::security::{HttpBuilder, HttpAuthScheme}; + /// # use utoipa::openapi::Deprecated; + /// HttpBuilder::new() + /// .scheme(HttpAuthScheme::Bearer) + /// .bearer_format("JWT") + /// .deprecated(Some(Deprecated::True)) + /// .build(); + /// ``` + pub fn deprecated(mut self, deprecated: Option) -> Self { + self.deprecated = deprecated; + self + } } /// Implements types according [RFC7235](https://datatracker.ietf.org/doc/html/rfc7235#section-5.1). @@ -390,6 +451,10 @@ pub struct OpenIdConnect { #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Declares whether the security scheme is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + pub deprecated: Option, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -408,6 +473,7 @@ impl OpenIdConnect { Self { open_id_connect_url: open_id_connect_url.into(), description: None, + deprecated: None, extensions: Default::default(), } } @@ -425,23 +491,48 @@ impl OpenIdConnect { Self { open_id_connect_url: open_id_connect_url.into(), description: Some(description.into()), + deprecated: None, extensions: Default::default(), } } + + /// Add or change deprecated status. + /// + /// # Examples + /// + /// Mark an OpenID Connect security scheme as deprecated. + /// ```rust + /// # use utoipa::openapi::security::OpenIdConnect; + /// # use utoipa::openapi::Deprecated; + /// OpenIdConnect::new("https://localhost/openid").deprecated(Some(Deprecated::True)); + /// ``` + pub fn deprecated(mut self, deprecated: Option) -> Self { + self.deprecated = deprecated; + self + } } /// OAuth2 [`Flow`] configuration for [`SecurityScheme`]. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] #[cfg_attr(feature = "debug", derive(Debug))] pub struct OAuth2 { /// Map of supported OAuth2 flows. pub flows: BTreeMap, + /// URL to OAuth2 authorization server metadata. + #[serde(skip_serializing_if = "Option::is_none")] + pub oauth2_metadata_url: Option, + /// Optional description for the [`OAuth2`] [`Flow`] [`SecurityScheme`]. #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Declares whether the security scheme is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + pub deprecated: Option, + /// Optional extensions "x-something". #[serde(skip_serializing_if = "Option::is_none", flatten)] pub extensions: Option, @@ -485,7 +576,9 @@ impl OAuth2 { .map(|auth_flow| (String::from(auth_flow.get_type_as_str()), auth_flow)), ), extensions: None, + oauth2_metadata_url: None, description: None, + deprecated: None, } } @@ -528,9 +621,55 @@ impl OAuth2 { .map(|auth_flow| (String::from(auth_flow.get_type_as_str()), auth_flow)), ), extensions: None, + oauth2_metadata_url: None, description: Some(description.into()), + deprecated: None, } } + + /// Add OAuth2 authorization server metadata URL. + /// + /// # Examples + /// + /// Add authorization server metadata URL to an existing [`OAuth2`] security scheme. + /// ```rust + /// # use utoipa::openapi::security::{OAuth2, Flow, Password, Scopes}; + /// OAuth2::new([Flow::Password( + /// Password::new( + /// "https://localhost/oauth/token", + /// Scopes::from_iter([("edit:items", "edit my items")]), + /// ), + /// )]) + /// .with_metadata_url("https://localhost/.well-known/oauth-authorization-server"); + /// ``` + pub fn with_metadata_url>(mut self, oauth2_metadata_url: S) -> Self { + self.oauth2_metadata_url = Some(oauth2_metadata_url.into()); + self + } + + /// Add or change deprecated status. + /// + /// Declaring a security scheme deprecated signals to API consumers that they should migrate + /// away from it. This is an OpenAPI 3.2 addition available on all [`SecurityScheme`] variants. + /// + /// # Examples + /// + /// Mark an [`OAuth2`] security scheme as deprecated. + /// ```rust + /// # use utoipa::openapi::security::{OAuth2, Flow, Password, Scopes}; + /// # use utoipa::openapi::Deprecated; + /// OAuth2::new([Flow::Password( + /// Password::new( + /// "https://localhost/oauth/token", + /// Scopes::from_iter([("edit:items", "edit my items")]), + /// ), + /// )]) + /// .deprecated(Some(Deprecated::True)); + /// ``` + pub fn deprecated(mut self, deprecated: Option) -> Self { + self.deprecated = deprecated; + self + } } /// [`OAuth2`] flow configuration object. @@ -550,6 +689,8 @@ pub enum Flow { ClientCredentials(ClientCredentials), /// Define authorization code [`Flow`] type. See [`AuthorizationCode::new`] for usage details. AuthorizationCode(AuthorizationCode), + /// Define device authorization [`Flow`] type. See [`DeviceAuthorization::new`] for usage details. + DeviceAuthorization(DeviceAuthorization), } impl Flow { @@ -559,6 +700,7 @@ impl Flow { Self::Password(_) => "password", Self::ClientCredentials(_) => "clientCredentials", Self::AuthorizationCode(_) => "authorizationCode", + Self::DeviceAuthorization(_) => "deviceAuthorization", } } } @@ -753,6 +895,98 @@ impl AuthorizationCode { } } +/// Device authorization [`Flow`] configuration for [`OAuth2`]. +#[non_exhaustive] +#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct DeviceAuthorization { + /// Device authorization endpoint URL for the flow. + pub device_authorization_url: String, + + /// Token URL for the flow. + pub token_url: String, + + /// Optional refresh token URL for the flow. + #[serde(skip_serializing_if = "Option::is_none")] + pub refresh_url: Option, + + /// Scopes required by the flow. + #[serde(flatten)] + pub scopes: Scopes, + + /// Optional extensions "x-something". + #[serde(skip_serializing_if = "Option::is_none", flatten)] + pub extensions: Option, +} + +impl DeviceAuthorization { + /// Construct a new device authorization OAuth2 flow. + /// + /// First parameter is the device authorization endpoint URL where the client requests a + /// device code, second parameter is the token URL used to poll for the access token, and the + /// third parameter defines the scopes available for the flow. + /// + /// # Examples + /// + /// Create a device authorization flow and use it in an [`OAuth2`] security scheme. + /// ```rust + /// # use utoipa::openapi::security::{OAuth2, Flow, DeviceAuthorization, Scopes}; + /// OAuth2::new([Flow::DeviceAuthorization( + /// DeviceAuthorization::new( + /// "https://localhost/oauth/device/code", + /// "https://localhost/oauth/token", + /// Scopes::from_iter([ + /// ("edit:items", "edit my items"), + /// ("read:items", "read my items"), + /// ]), + /// ), + /// )]); + /// ``` + pub fn new, T: Into>( + device_authorization_url: D, + token_url: T, + scopes: Scopes, + ) -> Self { + Self { + device_authorization_url: device_authorization_url.into(), + token_url: token_url.into(), + refresh_url: None, + scopes, + extensions: Default::default(), + } + } + + /// Construct a new device authorization OAuth2 flow with additional refresh URL. + /// + /// # Examples + /// + /// Create a device authorization flow with a refresh token URL. + /// ```rust + /// # use utoipa::openapi::security::{DeviceAuthorization, Scopes}; + /// DeviceAuthorization::with_refresh_url( + /// "https://localhost/oauth/device/code", + /// "https://localhost/oauth/token", + /// Scopes::from_iter([("edit:items", "edit my items")]), + /// "https://localhost/oauth/refresh", + /// ); + /// ``` + pub fn with_refresh_url>( + device_authorization_url: S, + token_url: S, + scopes: Scopes, + refresh_url: S, + ) -> Self { + Self { + device_authorization_url: device_authorization_url.into(), + token_url: token_url.into(), + refresh_url: Some(refresh_url.into()), + scopes, + extensions: Default::default(), + } + } +} + /// Password [`Flow`] configuration for [`OAuth2`]. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] @@ -1311,6 +1545,7 @@ mod tests { security_scheme_correct_mutual_tls: SecurityScheme::MutualTls { description: Some(String::from("authorization is performed with client side certificate")), + deprecated: None, extensions: None, }; r###"{ diff --git a/utoipa/src/openapi/server.rs b/utoipa/src/openapi/server.rs index 5b9f249e9..58030df8a 100644 --- a/utoipa/src/openapi/server.rs +++ b/utoipa/src/openapi/server.rs @@ -73,6 +73,10 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Optional name for the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Optional map of variable name and its substitution value used in [`Server::url`]. #[serde(skip_serializing_if = "Option::is_none")] pub variables: Option>, @@ -124,6 +128,11 @@ impl ServerBuilder { set_value!(self description description.map(|description| description.into())) } + /// Add or change name of the [`Server`]. + pub fn name>(mut self, name: Option) -> Self { + set_value!(self name name.map(|name| name.into())) + } + /// Add parameter to [`Server`] which is used to substitute values in [`Server::url`]. /// /// * `name` Defines name of the parameter which is being substituted within the url. If url has diff --git a/utoipa/src/openapi/tag.rs b/utoipa/src/openapi/tag.rs index 9ea2d187a..ed5dec3c7 100644 --- a/utoipa/src/openapi/tag.rs +++ b/utoipa/src/openapi/tag.rs @@ -21,10 +21,22 @@ builder! { /// Name of the tag. Should match to tag of **operation**. pub name: String, + /// Short summary for the tag. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, + /// Additional description for the tag shown in the document. #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, + /// Name of this tag's parent tag. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + + /// Kind of tag, allowing tooling to distinguish grouping tags from other tag purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + /// Additional external documentation for the tag. #[serde(skip_serializing_if = "Option::is_none")] pub external_docs: Option, @@ -51,11 +63,26 @@ impl TagBuilder { set_value!(self name name.into()) } + /// Add short summary for the tag. + pub fn summary>(mut self, summary: Option) -> Self { + set_value!(self summary summary.map(|summary| summary.into())) + } + /// Add additional description for the tag. pub fn description>(mut self, description: Option) -> Self { set_value!(self description description.map(|description| description.into())) } + /// Add parent tag name. + pub fn parent>(mut self, parent: Option) -> Self { + set_value!(self parent parent.map(|parent| parent.into())) + } + + /// Add tag kind. + pub fn kind>(mut self, kind: Option) -> Self { + set_value!(self kind kind.map(|kind| kind.into())) + } + /// Add additional external documentation for the tag. pub fn external_docs(mut self, external_docs: Option) -> Self { set_value!(self external_docs external_docs) diff --git a/utoipa/src/openapi/xml.rs b/utoipa/src/openapi/xml.rs index 8024f3301..26dad0192 100644 --- a/utoipa/src/openapi/xml.rs +++ b/utoipa/src/openapi/xml.rs @@ -30,6 +30,7 @@ builder! { #[non_exhaustive] #[derive(Serialize, Deserialize, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] + #[serde(rename_all = "camelCase")] pub struct Xml { /// Used to replace the name of attribute or type used in schema property. /// When used with [`Xml::wrapped`] attribute the name will be used as a wrapper name @@ -45,6 +46,10 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub prefix: Option>, + /// XML node type for this schema. + #[serde(skip_serializing_if = "Option::is_none")] + pub node_type: Option>, + /// Flag deciding will this attribute translate to element attribute instead of xml element. #[serde(skip_serializing_if = "Option::is_none")] pub attribute: Option, @@ -87,6 +92,13 @@ impl XmlBuilder { set_value!(self prefix prefix.map(|prefix| prefix.into())) } + /// Add [`Xml::node_type`] to xml object. + /// + /// Builder style chainable consuming add node type method. + pub fn node_type>>(mut self, node_type: Option) -> Self { + set_value!(self node_type node_type.map(|node_type| node_type.into())) + } + /// Mark [`Xml`] object as attribute. See [`Xml::attribute`]. /// /// Builder style chainable consuming add attribute method. diff --git a/utoipa/src/snapshots/utoipa__openapi__tests__merge_2_openapi_documents.snap b/utoipa/src/snapshots/utoipa__openapi__tests__merge_2_openapi_documents.snap index 7d4a76536..2563c5a65 100644 --- a/utoipa/src/snapshots/utoipa__openapi__tests__merge_2_openapi_documents.snap +++ b/utoipa/src/snapshots/utoipa__openapi__tests__merge_2_openapi_documents.snap @@ -1,7 +1,7 @@ --- source: utoipa/src/openapi.rs +assertion_line: 1161 expression: api_1 -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa/src/snapshots/utoipa__openapi__tests__merge_same_path_diff_methods.snap b/utoipa/src/snapshots/utoipa__openapi__tests__merge_same_path_diff_methods.snap index 2b04c9266..4ae21d41e 100644 --- a/utoipa/src/snapshots/utoipa__openapi__tests__merge_same_path_diff_methods.snap +++ b/utoipa/src/snapshots/utoipa__openapi__tests__merge_same_path_diff_methods.snap @@ -1,7 +1,7 @@ --- source: utoipa/src/openapi.rs +assertion_line: 1237 expression: api_1 -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa/src/snapshots/utoipa__openapi__tests__openapi_custom_extension.snap b/utoipa/src/snapshots/utoipa__openapi__tests__openapi_custom_extension.snap index abb471fea..4b626ba4e 100644 --- a/utoipa/src/snapshots/utoipa__openapi__tests__openapi_custom_extension.snap +++ b/utoipa/src/snapshots/utoipa__openapi__tests__openapi_custom_extension.snap @@ -1,7 +1,7 @@ --- source: utoipa/src/openapi.rs +assertion_line: 1295 expression: api -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_minimal_success.snap b/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_minimal_success.snap index cbc69b72d..3aed38f6f 100644 --- a/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_minimal_success.snap +++ b/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_minimal_success.snap @@ -1,7 +1,7 @@ --- source: utoipa/src/openapi.rs +assertion_line: 1067 expression: openapi -snapshot_kind: text --- { "openapi": "3.1.0", diff --git a/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_with_paths_success.snap b/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_with_paths_success.snap index 2db3e52b4..625dbdd56 100644 --- a/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_with_paths_success.snap +++ b/utoipa/src/snapshots/utoipa__openapi__tests__serialize_openapi_json_with_paths_success.snap @@ -1,7 +1,7 @@ --- source: utoipa/src/openapi.rs +assertion_line: 1098 expression: openapi -snapshot_kind: text --- { "openapi": "3.1.0",