From 640ef4407b52d8379d83894f6e42ea915adf0097 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 28 Jun 2026 18:44:30 +0200 Subject: [PATCH 01/26] fix: simplify utoipa-gen feature gates to fix jiff_0_2 (#1575) fix: simplify utoipa-gen feature gates to fix jiff_0_2 Enabling the "jiff_0_2" feature on its own would not correctly enable the more elaborate is_primitive branch because it was mistakenly omitted from the feature gate list. Rather than merely fixing the feature gate list, this commit simplifies the logic to make such a mistake impossible in the future. --- utoipa-gen/CHANGELOG.md | 1 + utoipa-gen/src/schema_type.rs | 31 ++----------------------------- 2 files changed, 3 insertions(+), 29 deletions(-) diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index becadff2..81b4c371 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -19,6 +19,7 @@ ### Fixed * 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 diff --git a/utoipa-gen/src/schema_type.rs b/utoipa-gen/src/schema_type.rs index f84acbb0..e6e5f750 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); From fb812a11ab288a07f3170a665c3f809b17a7489d Mon Sep 17 00:00:00 2001 From: John Vandenberg Date: Wed, 1 Jul 2026 03:00:24 +0800 Subject: [PATCH 02/26] fix: workaround time/cookie incompatibility (#1577) * fix: workaround time/cookie incompatibility * Also fix examples --- Cargo.toml | 6 ++++++ examples/actix-web-multipart/Cargo.toml | 2 ++ examples/actix-web-multiple-api-docs-with-scopes/Cargo.toml | 2 ++ examples/actix-web-scopes-binding/Cargo.toml | 2 ++ examples/generics-actix/Cargo.toml | 2 ++ examples/raw-json-actix/Cargo.toml | 2 ++ examples/rocket-todo/Cargo.toml | 2 ++ examples/simple-x-extensions/Cargo.toml | 2 ++ examples/todo-actix/Cargo.toml | 2 ++ utoipa-gen/Cargo.toml | 2 +- utoipa-rapidoc/Cargo.toml | 5 +++++ utoipa-redoc/Cargo.toml | 5 +++++ utoipa-scalar/Cargo.toml | 5 +++++ utoipa-swagger-ui/Cargo.toml | 4 ++++ 14 files changed, 42 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index e4b7dc16..5595ba7d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,12 @@ 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.metadata.publish] order = [ "utoipa-config", diff --git a/examples/actix-web-multipart/Cargo.toml b/examples/actix-web-multipart/Cargo.toml index 73cf57fd..01c7f90b 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 1984b3d5..5d4e80d8 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 4e417f82..ba2f8386 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 58c3e186..eb3ab245 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/raw-json-actix/Cargo.toml b/examples/raw-json-actix/Cargo.toml index 6fa2d8f2..a52704a0 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 5e159d07..c8ae9e88 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 6bbedc5d..9f223768 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/todo-actix/Cargo.toml b/examples/todo-actix/Cargo.toml index 520af46c..4cf29a50 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/utoipa-gen/Cargo.toml b/utoipa-gen/Cargo.toml index f1f1949a..3f8479f5 100644 --- a/utoipa-gen/Cargo.toml +++ b/utoipa-gen/Cargo.toml @@ -51,7 +51,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"] } diff --git a/utoipa-rapidoc/Cargo.toml b/utoipa-rapidoc/Cargo.toml index cb97b6f4..33061ce7 100644 --- a/utoipa-rapidoc/Cargo.toml +++ b/utoipa-rapidoc/Cargo.toml @@ -15,6 +15,10 @@ 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" } @@ -23,6 +27,7 @@ utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, feat ] } 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 } diff --git a/utoipa-redoc/Cargo.toml b/utoipa-redoc/Cargo.toml index fb01f663..c607381a 100644 --- a/utoipa-redoc/Cargo.toml +++ b/utoipa-redoc/Cargo.toml @@ -15,6 +15,10 @@ 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" } @@ -23,6 +27,7 @@ utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, feat ] } 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] diff --git a/utoipa-scalar/Cargo.toml b/utoipa-scalar/Cargo.toml index 4a33c4fb..81fb7c27 100644 --- a/utoipa-scalar/Cargo.toml +++ b/utoipa-scalar/Cargo.toml @@ -15,6 +15,10 @@ 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" } @@ -23,6 +27,7 @@ utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, feat ] } 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] diff --git a/utoipa-swagger-ui/Cargo.toml b/utoipa-swagger-ui/Cargo.toml index 9bfab9e2..cce27f45 100644 --- a/utoipa-swagger-ui/Cargo.toml +++ b/utoipa-swagger-ui/Cargo.toml @@ -21,6 +21,8 @@ vendored = ["dep:utoipa-swagger-ui-vendored"] cache = ["dep:dirs", "dep:sha2"] 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,6 +30,8 @@ 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 } From 205fe71fbcae68e0eab146e90ab9b29859c61647 Mon Sep 17 00:00:00 2001 From: Jaye Date: Sun, 5 Jul 2026 23:50:23 +0100 Subject: [PATCH 03/26] fix: emit vec![] instead of array literals to avoid large stack arrays (#1580) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix stack overflow * fix: emit vec![] instead of array literals to avoid large stack arrays Wide structs/enums generated huge `[..]` array literals in ToSchema/IntoParams, tripping clippy::large_stack_arrays and overflowing the stack. Make the Array tokenizer emit vec![] and deny the lint so it doesn't regress again (#1454). * chore: not really testing so just smoke test --------- Co-authored-by: Rafał Mikrut Co-authored-by: Jaye Park --- Cargo.toml | 8 ++++++ utoipa-actix-web/Cargo.toml | 4 +-- utoipa-axum/Cargo.toml | 4 +-- utoipa-config/Cargo.toml | 4 +-- utoipa-gen/CHANGELOG.md | 1 + utoipa-gen/Cargo.toml | 4 +-- utoipa-gen/src/component/into_params.rs | 6 ++--- utoipa-gen/src/component/schema/enums.rs | 3 +-- utoipa-gen/src/lib.rs | 27 +++++++++---------- utoipa-gen/tests/schema_derive_test.rs | 33 ++++++++++++++++++++++++ utoipa-rapidoc/Cargo.toml | 4 +-- utoipa-redoc/Cargo.toml | 4 +-- utoipa-scalar/Cargo.toml | 4 +-- utoipa-swagger-ui-vendored/Cargo.toml | 3 +++ utoipa-swagger-ui/Cargo.toml | 4 +-- utoipa/Cargo.toml | 4 +-- 16 files changed, 81 insertions(+), 36 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5595ba7d..c032528d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,14 @@ members = [ [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" + [workspace.metadata.publish] order = [ "utoipa-config", diff --git a/utoipa-actix-web/Cargo.toml b/utoipa-actix-web/Cargo.toml index 5d2055e5..92f02e64 100644 --- a/utoipa-actix-web/Cargo.toml +++ b/utoipa-actix-web/Cargo.toml @@ -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-axum/Cargo.toml b/utoipa-axum/Cargo.toml index 992dd766..0d585e4f 100644 --- a/utoipa-axum/Cargo.toml +++ b/utoipa-axum/Cargo.toml @@ -43,5 +43,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-config/Cargo.toml b/utoipa-config/Cargo.toml index 7bbfbc69..4d8f3814 100644 --- a/utoipa-config/Cargo.toml +++ b/utoipa-config/Cargo.toml @@ -19,5 +19,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-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 81b4c371..2a648045 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -18,6 +18,7 @@ ### Fixed +* 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) diff --git a/utoipa-gen/Cargo.toml b/utoipa-gen/Cargo.toml index 3f8479f5..ebf45410 100644 --- a/utoipa-gen/Cargo.toml +++ b/utoipa-gen/Cargo.toml @@ -83,5 +83,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/into_params.rs b/utoipa-gen/src/component/into_params.rs index 6e079f9b..64237356 100644 --- a/utoipa-gen/src/component/into_params.rs +++ b/utoipa-gen/src/component/into_params.rs @@ -27,7 +27,7 @@ use crate::{ doc_comment::CommentAttributes, parse_utils::LitBoolOrExprPath, token_stream::{quote_diagnostics, Diagnostics, ToTokensDiagnostics}, - Array, OptionExt, Required, + OptionExt, Required, }; use super::{ @@ -155,12 +155,12 @@ impl ToTokensDiagnostics for IntoParams { Ok(param.to_token_stream()) }) - .collect::, Diagnostics>>()?; + .collect::, Diagnostics>>()?; tokens.extend(quote! { impl #impl_generics utoipa::IntoParams for #ident #ty_generics #where_clause { fn into_params(parameter_in_provider: impl Fn() -> Option) -> Vec { - #params.into_iter().filter(Option::is_some).flatten().collect() + vec![#(#params),*].into_iter().filter(Option::is_some).flatten().collect() } } }); diff --git a/utoipa-gen/src/component/schema/enums.rs b/utoipa-gen/src/component/schema/enums.rs index de9df467..59a8b2da 100644 --- a/utoipa-gen/src/component/schema/enums.rs +++ b/utoipa-gen/src/component/schema/enums.rs @@ -969,11 +969,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/lib.rs b/utoipa-gen/src/lib.rs index 0b688c12..3c7dffd5 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}, @@ -3164,17 +3164,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] }); } } diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 6717ddde..459fbea8 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -3651,3 +3651,36 @@ 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"); +} diff --git a/utoipa-rapidoc/Cargo.toml b/utoipa-rapidoc/Cargo.toml index 33061ce7..33739157 100644 --- a/utoipa-rapidoc/Cargo.toml +++ b/utoipa-rapidoc/Cargo.toml @@ -35,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-redoc/Cargo.toml b/utoipa-redoc/Cargo.toml index c607381a..b7ab9d43 100644 --- a/utoipa-redoc/Cargo.toml +++ b/utoipa-redoc/Cargo.toml @@ -33,5 +33,5 @@ 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-scalar/Cargo.toml b/utoipa-scalar/Cargo.toml index 81fb7c27..d0355493 100644 --- a/utoipa-scalar/Cargo.toml +++ b/utoipa-scalar/Cargo.toml @@ -33,5 +33,5 @@ axum = { version = "0.8.4", default-features = false, optional = true } [dev-dependencies] 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-swagger-ui-vendored/Cargo.toml b/utoipa-swagger-ui-vendored/Cargo.toml index 186d8752..c23e8c2f 100644 --- a/utoipa-swagger-ui-vendored/Cargo.toml +++ b/utoipa-swagger-ui-vendored/Cargo.toml @@ -11,4 +11,7 @@ categories = ["web-programming"] authors = ["Juha Kukkonen "] rust-version.workspace = true +[lints] +workspace = true + [dependencies] diff --git a/utoipa-swagger-ui/Cargo.toml b/utoipa-swagger-ui/Cargo.toml index cce27f45..bb51e645 100644 --- a/utoipa-swagger-ui/Cargo.toml +++ b/utoipa-swagger-ui/Cargo.toml @@ -72,5 +72,5 @@ reqwest = { version = "0.13", features = [ url = { version = "2", optional = true } utoipa-swagger-ui-vendored = { version = "0.1", 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/Cargo.toml b/utoipa/Cargo.toml index 18fd3dc0..e0d1f591 100644 --- a/utoipa/Cargo.toml +++ b/utoipa/Cargo.toml @@ -83,5 +83,5 @@ features = [ ] rustdoc-args = ["--cfg", "doc_cfg"] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(doc_cfg)'] } +[lints] +workspace = true From 5b25257cd3da124aff8747a843b1a688b3ce8f63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Jankiewicz?= Date: Sun, 9 Aug 2026 20:48:47 +0200 Subject: [PATCH 04/26] Add OpenAPI 3.2 support (#1555) * Add OpenAPI 3.2 support * Fix OpenAPI 3.2 CI failures * ci: re-trigger build after upstream time 0.3.48 yank The 2026-06-12 CI run resolved time 0.3.48 (the repo intentionally does not commit a root Cargo.lock, so CI takes the latest deps). time 0.3.48 shipped an E0119 trait-coherence regression that broke the cookie crate, failing the utoipa-gen and examples jobs (and cancelling utoipa via fail-fast). time 0.3.48 has since been yanked and 0.3.49 published. This empty commit re-runs CI to pick up the fixed resolution; verified locally that the full utoipa-gen matrix and example compilation pass with time 0.3.49. * Address review feedback on OpenAPI 3.2 support - Keep `Version31` as the default OpenApiVersion; `Version32` is now opt-in (no deprecation). Reverts the default-output version back to 3.1.0 so the change is non-breaking until 3.2 tooling support is widespread. - Add `OpenApiBuilder::openapi(..)` so 3.2 output can be opted into. - Rename `self_url` field/builder to `self_uri` to match the spec wording. - Simplify `OpenApiVersion` deserialize with slice `matches!` patterns. - Drop redundant non-empty check when merging `additional_operations`. - Use `RefOr::T(parameter.into())` instead of the double `.into().into()`. - Tidy `HttpBuilder::deprecated` formatting. - Revert the actix `#[utoipa::path]` doc examples from `rust,ignore` back to `rust` (they pass under the `actix_extras` feature CI runs). --- examples/simple-x-extensions/src/main.rs | 24 +- utoipa-gen/src/openapi.rs | 29 +- utoipa-gen/src/path/example.rs | 27 +- utoipa-gen/src/path/media_type.rs | 1 - utoipa-gen/src/path/parameter.rs | 27 +- utoipa-gen/src/path/response/header.rs | 2 +- ..._derive_openapi_with_generic_response.snap | 5 +- ...rive__derive_path_with_response_links.snap | 8 +- ...cket_path_with_query_params_in_option.snap | 6 +- ...tiple_examples_auto_collect_schemas-2.snap | 5 +- ...nt_attribute_auto_collect_responses-2.snap | 5 +- ...iple_responses_with_multiple_examples.snap | 5 +- ...ath_response_default_no_value_nor_ref.snap | 6 +- ...test__path_response_with_external_ref.snap | 5 +- ...t__path_response_with_inline_ref_type.snap | 5 +- ...ve_test__path_response_with_no_schema.snap | 5 +- ...nse_derive_test__derive_enum_response.snap | 3 +- ...esponses_enum_with_multiple_responses.snap | 12 +- ...esponses_unnamed_struct_inline_schema.snap | 5 +- ...o_responses_unnamed_struct_ref_schema.snap | 5 +- ..._responses_unnamed_struct_to_response.snap | 5 +- ..._unnamed_struct_with_primitive_schema.snap | 5 +- ...ive_test__derive_name_struct_response.snap | 3 +- ...st__derive_response_multiple_examples.snap | 3 +- ...t__derive_response_with_enum_contents.snap | 3 +- ...e_response_with_enum_contents_inlined.snap | 3 +- ...e_response_with_inline_unnamed_schema.snap | 3 +- ..._test__derive_response_with_unit_type.snap | 6 +- ..._test__derive_unnamed_struct_response.snap | 3 +- ..._collect_recursive_schema_not_inlined.snap | 2 +- ...__derive_generic_schema_enum_variants.snap | 2 +- ...generics__generic_request_body_schema.snap | 2 +- ...ema_generics__generic_schema_full_api.snap | 4 +- .../schema_generics__high_order_types.snap | 2 +- ...enerics__schema_with_non_generic_root.snap | 2 +- utoipa/src/openapi.rs | 690 +++++++++++++++++- utoipa/src/openapi/content.rs | 52 ++ utoipa/src/openapi/encoding.rs | 49 +- utoipa/src/openapi/example.rs | 22 + utoipa/src/openapi/header.rs | 24 +- utoipa/src/openapi/link.rs | 1 + utoipa/src/openapi/path.rs | 196 ++++- utoipa/src/openapi/request_body.rs | 28 +- utoipa/src/openapi/response.rs | 42 +- utoipa/src/openapi/schema.rs | 161 +++- utoipa/src/openapi/security.rs | 127 +++- utoipa/src/openapi/server.rs | 9 + utoipa/src/openapi/tag.rs | 27 + utoipa/src/openapi/xml.rs | 12 + ...api__tests__merge_2_openapi_documents.snap | 2 +- ...__tests__merge_same_path_diff_methods.snap | 2 +- ...napi__tests__openapi_custom_extension.snap | 2 +- ...erialize_openapi_json_minimal_success.snap | 2 +- ...alize_openapi_json_with_paths_success.snap | 2 +- 54 files changed, 1539 insertions(+), 149 deletions(-) diff --git a/examples/simple-x-extensions/src/main.rs b/examples/simple-x-extensions/src/main.rs index 9ac424d5..4140f8b0 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/utoipa-gen/src/openapi.rs b/utoipa-gen/src/openapi.rs index 048e764c..2144bc46 100644 --- a/utoipa-gen/src/openapi.rs +++ b/utoipa-gen/src/openapi.rs @@ -213,14 +213,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 +234,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 +272,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)) diff --git a/utoipa-gen/src/path/example.rs b/utoipa-gen/src/path/example.rs index c15793e1..27ffb43c 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 5a2aeda7..bcb37dac 100644 --- a/utoipa-gen/src/path/media_type.rs +++ b/utoipa-gen/src/path/media_type.rs @@ -208,7 +208,6 @@ impl ToTokensDiagnostics for MediaTypeAttr<'_> { #examples #(#encoding)* #extensions - .into() }); Ok(()) diff --git a/utoipa-gen/src/path/parameter.rs b/utoipa-gen/src/path/parameter.rs index 8ab583c2..514e59e9 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/header.rs b/utoipa-gen/src/path/response/header.rs index 053e9a5b..429b2ae1 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/tests/snapshots/openapi_derive__derive_openapi_with_generic_response.snap b/utoipa-gen/tests/snapshots/openapi_derive__derive_openapi_with_generic_response.snap index c865a3c9..bcee0101 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_path_with_response_links.snap b/utoipa-gen/tests/snapshots/path_derive__derive_path_with_response_links.snap index c4fa23d3..7f25455c 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_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 d0eb4333..1d1ce735 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 90eacbb4..e3c2d0d0 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 b24f69a3..60aa4d6f 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 f3c2b002..a8beb799 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 88aa28e0..d8907d4b 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 d53fc73a..3573f325 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 4026e55e..e46da53a 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 40537af5..58601016 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 1b5b2a54..fe4dcded 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 fda10ace..48902f27 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 11f335f5..d24bce66 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 84b7ae4b..14053556 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 11f335f5..3e95f0fd 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 1637584c..265cb19b 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 2cf9bd03..da6ea16a 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 c2abefb7..58ff4894 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 695ba27b..0152a299 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 a9d4ef80..4154c48a 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 73c266f9..c36290fe 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 f61f3dbd..0bd92b76 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 635aa013..a5752735 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_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 8043cb14..74a8afb2 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 683a1fd2..2acd4a0c 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 2111c5f1..2c4540d9 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 c0bf8c91..f58d52de 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 749770db..e5c6eecb 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 3b31c83e..fcc71abd 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/src/openapi.rs b/utoipa/src/openapi.rs index 62bc0ba5..6568e259 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,11 @@ builder! { /// See more details at . pub paths: Paths, + /// Incoming requests that may be initiated by the API provider independently of an + /// incoming API request. + #[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 +124,10 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub external_docs: Option, + /// The default JSON Schema dialect used by Schema Objects in this OpenAPI document. + #[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 +135,10 @@ builder! { #[serde(rename = "$schema", default, skip_serializing_if = "String::is_empty")] pub schema: String, + /// URI identifying this OpenAPI document. + #[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 +334,14 @@ 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. + 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 +357,11 @@ impl OpenApiBuilder { set_value!(self paths paths.into()) } + /// Add [`Paths`] to describe incoming requests that may be initiated by the API provider. + 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 +399,16 @@ 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. + 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. + 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 +417,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 +437,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 +456,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 +698,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 f40bd48f..d5e478f5 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 d63a5a04..28bb1909 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 b233aa56..989a0a6a 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 7417eb8d..395a16b2 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 365d157c..9a53da55 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 79bac8af..e4d50d7a 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, parameters: Option) -> Self { + set_value!(self parameters parameters.map(|parameters| parameters.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 6f21de63..ff148e0d 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 62239b37..918f3fb5 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 81e36df7..3ad3e18a 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,92 @@ impl ComponentsBuilder { self.response(name, response) } + /// Add [`Content`] to [`Components`] as a reusable media type object. + 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. + 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`]. + 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`]. + 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`]. + 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`]. + 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`]. + 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`]. + 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`]. + 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 +379,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 +1218,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 +1444,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 +1876,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 +1905,7 @@ impl Default for Array { extensions: Default::default(), content_encoding: Default::default(), content_media_type: Default::default(), + content_schema: Default::default(), } } } @@ -1901,6 +2046,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) @@ -2486,6 +2636,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 963ea98d..f6677dbc 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. /// @@ -185,6 +185,9 @@ pub enum SecurityScheme { #[allow(missing_docs)] #[serde(skip_serializing_if = "Option::is_none")] description: Option, + #[allow(missing_docs)] + #[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 +219,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 +242,7 @@ impl ApiKeyValue { Self { name: name.into(), description: None, + deprecated: None, extensions: Default::default(), } } @@ -252,9 +260,16 @@ impl ApiKeyValue { Self { name: name.into(), description: Some(description.into()), + deprecated: None, extensions: Default::default(), } } + + /// Add or change deprecated status. + pub fn deprecated(mut self, deprecated: Option) -> Self { + self.deprecated = deprecated; + self + } } builder! { @@ -279,6 +294,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 +321,7 @@ impl Http { scheme, bearer_format: None, description: None, + deprecated: None, extensions: Default::default(), } } @@ -347,6 +367,12 @@ impl HttpBuilder { self } + + /// Add or change deprecated status. + 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 +416,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 +438,7 @@ impl OpenIdConnect { Self { open_id_connect_url: open_id_connect_url.into(), description: None, + deprecated: None, extensions: Default::default(), } } @@ -425,23 +456,39 @@ 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. + 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 +532,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 +577,23 @@ 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. + 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. + pub fn deprecated(mut self, deprecated: Option) -> Self { + self.deprecated = deprecated; + self + } } /// [`OAuth2`] flow configuration object. @@ -550,6 +613,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 +624,7 @@ impl Flow { Self::Password(_) => "password", Self::ClientCredentials(_) => "clientCredentials", Self::AuthorizationCode(_) => "authorizationCode", + Self::DeviceAuthorization(_) => "deviceAuthorization", } } } @@ -753,6 +819,64 @@ 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. + 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. + 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 +1435,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 5b9f249e..58030df8 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 9ea2d187..ed5dec3c 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 8024f330..26dad019 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 7d4a7653..2563c5a6 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 2b04c926..4ae21d41 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 abb471fe..4b626ba4 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 cbc69b72..3aed38f6 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 2db3e52b..625dbdd5 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", From 58632b1c7d29443bcc83b11a026fdd13eb09742c Mon Sep 17 00:00:00 2001 From: Jaye Date: Sun, 9 Aug 2026 22:08:38 +0100 Subject: [PATCH 05/26] docs: add examples and changelog for PR-1555 (#1590) * docs: add examples and changelog * test: fix empty description being omitted * chore: change parameters to refs --- .../testdata/app_generated_openapi | 4 - utoipa-gen/CHANGELOG.md | 6 + utoipa/CHANGELOG.md | 7 + utoipa/src/openapi.rs | 69 ++++++++- utoipa/src/openapi/path.rs | 4 +- utoipa/src/openapi/schema.rs | 137 ++++++++++++++++++ utoipa/src/openapi/security.rs | 114 ++++++++++++++- 7 files changed, 330 insertions(+), 11 deletions(-) diff --git a/utoipa-actix-web/testdata/app_generated_openapi b/utoipa-actix-web/testdata/app_generated_openapi index 16373c64..26cd2a58 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-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 2a648045..51a2afe0 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -4,6 +4,10 @@ ### Added +* 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) @@ -13,6 +17,8 @@ ### Changed +* 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) diff --git a/utoipa/CHANGELOG.md b/utoipa/CHANGELOG.md index 89bbf7bb..03dc2b76 100644 --- a/utoipa/CHANGELOG.md +++ b/utoipa/CHANGELOG.md @@ -7,6 +7,13 @@ to look into changes introduced to **`utoipa-gen`**. ### 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) diff --git a/utoipa/src/openapi.rs b/utoipa/src/openapi.rs index 6568e259..0aee6ecb 100644 --- a/utoipa/src/openapi.rs +++ b/utoipa/src/openapi.rs @@ -92,7 +92,13 @@ builder! { pub paths: Paths, /// Incoming requests that may be initiated by the API provider independently of an - /// incoming API request. + /// 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, @@ -124,7 +130,11 @@ builder! { #[serde(skip_serializing_if = "Option::is_none")] pub external_docs: Option, - /// The default JSON Schema dialect used by Schema Objects in this OpenAPI document. + /// 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, @@ -135,7 +145,10 @@ builder! { #[serde(rename = "$schema", default, skip_serializing_if = "String::is_empty")] pub schema: String, - /// URI identifying this OpenAPI document. + /// 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, @@ -338,6 +351,17 @@ impl OpenApiBuilder { /// /// 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) } @@ -358,6 +382,27 @@ impl OpenApiBuilder { } /// 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)) } @@ -401,11 +446,29 @@ impl OpenApiBuilder { } /// 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)) } diff --git a/utoipa/src/openapi/path.rs b/utoipa/src/openapi/path.rs index e4d50d7a..dabbfab6 100644 --- a/utoipa/src/openapi/path.rs +++ b/utoipa/src/openapi/path.rs @@ -466,8 +466,8 @@ impl PathItemBuilder { } /// Append list of parameter references common to all [`Operation`]s to this [`PathItem`]. - pub fn parameter_refs>(mut self, parameters: Option) -> Self { - set_value!(self parameters parameters.map(|parameters| parameters.into_iter().map(RefOr::Ref).collect())) + 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`]. diff --git a/utoipa/src/openapi/schema.rs b/utoipa/src/openapi/schema.rs index 3ad3e18a..29bb832f 100644 --- a/utoipa/src/openapi/schema.rs +++ b/utoipa/src/openapi/schema.rs @@ -267,6 +267,25 @@ impl ComponentsBuilder { } /// 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, @@ -277,6 +296,22 @@ impl ComponentsBuilder { } /// 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, @@ -295,6 +330,22 @@ impl ComponentsBuilder { } /// 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, @@ -305,6 +356,15 @@ impl ComponentsBuilder { } /// 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, @@ -315,6 +375,25 @@ impl ComponentsBuilder { } /// 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, @@ -325,18 +404,62 @@ impl ComponentsBuilder { } /// 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, @@ -347,6 +470,20 @@ impl ComponentsBuilder { } /// 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 diff --git a/utoipa/src/openapi/security.rs b/utoipa/src/openapi/security.rs index f6677dbc..d01c5420 100644 --- a/utoipa/src/openapi/security.rs +++ b/utoipa/src/openapi/security.rs @@ -180,12 +180,25 @@ 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, - #[allow(missing_docs)] + /// Declares whether the security scheme is deprecated. #[serde(skip_serializing_if = "Option::is_none")] deprecated: Option, /// Optional extensions "x-something". @@ -266,6 +279,15 @@ impl ApiKeyValue { } /// 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 @@ -369,6 +391,19 @@ impl HttpBuilder { } /// 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 @@ -462,6 +497,15 @@ impl OpenIdConnect { } /// 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 @@ -584,12 +628,44 @@ impl OAuth2 { } /// 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 @@ -846,6 +922,27 @@ pub struct DeviceAuthorization { 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, @@ -861,6 +958,19 @@ impl DeviceAuthorization { } /// 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, From c607078f121a11267b7511d6655f9bd693738446 Mon Sep 17 00:00:00 2001 From: Jack Ullery <46848683+jack-ullery@users.noreply.github.com> Date: Mon, 10 Aug 2026 07:43:51 -0400 Subject: [PATCH 06/26] feat: support generic types with `IntoParams` (#1588) * add example for IntoParams with generic argument * add automated test * working example of generic params it breaks everything else which is a bummer * fix implementation with into_params * update unit tests to pin behavior * minor code cleaning * remove example code I assume a reviewer might call this superfluous. This code was useful for testing locally. * shorten code * fix warning * add basic changelog --- utoipa-gen/CHANGELOG.md | 1 + utoipa-gen/src/component/into_params.rs | 19 ++++++++- utoipa-gen/tests/path_derive.rs | 40 +++++++++++++++++++ ...derive_into_params_with_generic_field.snap | 33 +++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 utoipa-gen/tests/snapshots/path_derive__derive_into_params_with_generic_field.snap diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 51a2afe0..2ee6a3a4 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -4,6 +4,7 @@ ### Added +* 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 diff --git a/utoipa-gen/src/component/into_params.rs b/utoipa-gen/src/component/into_params.rs index 64237356..61c9abb8 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::{ @@ -157,9 +157,11 @@ impl ToTokensDiagnostics for IntoParams { }) .collect::, Diagnostics>>()?; + 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 generics: Vec> = vec![ #(#generic_schemas),* ]; vec![#(#params),*].into_iter().filter(Option::is_some).flatten().collect() } } @@ -169,6 +171,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 diff --git a/utoipa-gen/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index 676a4d65..3e5e82a9 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -1973,6 +1973,46 @@ fn derive_into_params_with_ignored_struct_fn_field() { assert_json_snapshot!(value); } +#[test] +fn derive_into_params_with_generic_field() { + #[derive(ToSchema)] + #[allow(unused)] + enum Bird { + Sparrow, + Pigeon, + Crow, + Coot, + } + + #[derive(ToSchema)] + #[allow(unused)] + enum Beetle { + Stag, + Longhorn, + Weevil, + } + + #[derive(IntoParams)] + #[into_params(parameter_in = Query)] + #[allow(unused)] + struct QueryParams { + animal: AnimalType, + } + + #[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"); + + assert_json_snapshot!(operation); +} + #[test] fn derive_octet_stream_request_body() { #![allow(dead_code)] 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 00000000..adf3e9fe --- /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" + } + } +] From e092565a9724b07a5ebf122e80ffa3d70addbe5d Mon Sep 17 00:00:00 2001 From: Jaye Date: Mon, 10 Aug 2026 17:46:19 +0100 Subject: [PATCH 07/26] feat(gen): allow opting into OpenAPI 3.2 output via the version attribute (#1591) --- utoipa-gen/CHANGELOG.md | 1 + utoipa-gen/src/lib.rs | 4 ++ utoipa-gen/src/openapi.rs | 68 +++++++++++++++++++++++++++++- utoipa-gen/tests/openapi_derive.rs | 26 ++++++++++++ 4 files changed, 98 insertions(+), 1 deletion(-) diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 2ee6a3a4..4de4d217 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -4,6 +4,7 @@ ### Added +* 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 diff --git a/utoipa-gen/src/lib.rs b/utoipa-gen/src/lib.rs index 3c7dffd5..8fb4a229 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -2008,6 +2008,9 @@ 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. /// /// /// OpenApi derive macro will also derive [`Info`][info] for OpenApi specification using Cargo @@ -2221,6 +2224,7 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// /// [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 diff --git a/utoipa-gen/src/openapi.rs b/utoipa-gen/src/openapi.rs index 2144bc46..5a9d48db 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, @@ -46,6 +47,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; } @@ -84,7 +88,7 @@ pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Result 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, version"; let mut openapi = OpenApiAttr::default(); while !input.is_empty() { @@ -99,6 +103,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)?; } @@ -146,6 +153,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); @@ -426,6 +482,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) @@ -448,6 +513,7 @@ impl ToTokensDiagnostics for OpenApi<'_> { fn openapi() -> utoipa::openapi::OpenApi { use utoipa::{ToSchema, Path}; let mut openapi = utoipa::openapi::OpenApiBuilder::new() + #version .info(#info) .paths({ #path_items diff --git a/utoipa-gen/tests/openapi_derive.rs b/utoipa-gen/tests/openapi_derive.rs index 8e09e557..c2a7b9d2 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 { From b66879abc4ae14e4d2b185ec314570a7cdfb2fed Mon Sep 17 00:00:00 2001 From: Jaye Date: Mon, 10 Aug 2026 18:01:39 +0100 Subject: [PATCH 08/26] feat(gen): support item_schema attribute for streaming/SSE response types (#1592) * feat(gen): support item_schema attribute for streaming/SSE response types * chore: update sse example to use programmatic openapi 3.2 version mapping * chore: use openapi version attribute As https://github.com/juhaku/utoipa/pull/1591/ is merged, I can remove `api.openapi = utoipa::openapi::OpenApiVersion::Version32;` from the example to replace with `#[openapi(version = "3.2.0", components(schemas(PetEvent)))]`. --- examples/openapi-3_2-sse/Cargo.toml | 22 +++++ examples/openapi-3_2-sse/README.md | 15 ++++ examples/openapi-3_2-sse/src/main.rs | 124 +++++++++++++++++++++++++++ utoipa-gen/CHANGELOG.md | 1 + utoipa-gen/src/lib.rs | 9 ++ utoipa-gen/src/path/media_type.rs | 36 ++++++-- utoipa-gen/src/path/response.rs | 3 +- 7 files changed, 203 insertions(+), 7 deletions(-) create mode 100644 examples/openapi-3_2-sse/Cargo.toml create mode 100644 examples/openapi-3_2-sse/README.md create mode 100644 examples/openapi-3_2-sse/src/main.rs diff --git a/examples/openapi-3_2-sse/Cargo.toml b/examples/openapi-3_2-sse/Cargo.toml new file mode 100644 index 00000000..df192dd4 --- /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 00000000..17c4f984 --- /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 00000000..1546d3e7 --- /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/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 4de4d217..b86d4bf4 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -4,6 +4,7 @@ ### 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) diff --git a/utoipa-gen/src/lib.rs b/utoipa-gen/src/lib.rs index 8fb4a229..576f92f9 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -1154,6 +1154,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 +1888,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 diff --git a/utoipa-gen/src/path/media_type.rs b/utoipa-gen/src/path/media_type.rs index bcb37dac..a4956e39 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,6 +227,7 @@ impl ToTokensDiagnostics for MediaTypeAttr<'_> { tokens.extend(quote! { utoipa::openapi::content::ContentBuilder::new() #schema_tokens + #item_schema_tokens #example #examples #(#encoding)* diff --git a/utoipa-gen/src/path/response.rs b/utoipa-gen/src/path/response.rs index d925abf1..cb13396e 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()?; From e8a26bb74f66fa2eaaa88d40999b9c519e41fc60 Mon Sep 17 00:00:00 2001 From: Nipunn Koorapati Date: Mon, 24 Aug 2026 12:36:23 -0700 Subject: [PATCH 09/26] Recursively discover flattened fields in maps (#1582) * Recursively discover flattened fields in maps This allows the discovered fields to appear in component.schemas without having to explicitly list it as a workaround. Fixes #1330 * Use assert_value * Apply suggestion from @CommanderStorm Co-authored-by: Frank Elsinga --------- Co-authored-by: Frank Elsinga --- utoipa-gen/src/component.rs | 9 +++++++-- utoipa-gen/src/component/schema.rs | 3 +++ utoipa-gen/tests/schema_derive_test.rs | 28 ++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/utoipa-gen/src/component.rs b/utoipa-gen/src/component.rs index 7f9ef253..e102e653 100644 --- a/utoipa-gen/src/component.rs +++ b/utoipa-gen/src/component.rs @@ -1576,6 +1576,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 +1599,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 +1610,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 +1623,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/schema.rs b/utoipa-gen/src/component/schema.rs index 191b59c4..4d393332 100644 --- a/utoipa-gen/src/component/schema.rs +++ b/utoipa-gen/src/component/schema.rs @@ -388,6 +388,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, } }) diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 459fbea8..710434c0 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! { From 5db2ccbe9a16bcac8c03c5853fc4612f0eec5126 Mon Sep 17 00:00:00 2001 From: n4n5 Date: Mon, 24 Aug 2026 21:52:16 +0200 Subject: [PATCH 10/26] Refactor documentation in lib.rs (#1581) Updated documentation comments to remove commented-out code. --- utoipa-axum/src/lib.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/utoipa-axum/src/lib.rs b/utoipa-axum/src/lib.rs index dff2430b..e36562b4 100644 --- a/utoipa-axum/src/lib.rs +++ b/utoipa-axum/src/lib.rs @@ -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, From 0a5951b936c2e99ff94964da949b333a776689a7 Mon Sep 17 00:00:00 2001 From: Jaye Date: Mon, 24 Aug 2026 21:00:50 +0100 Subject: [PATCH 11/26] chore: Update CHANGELOG.md (#1596) Add the following entry in utoipa-gen/CHANGELOG.md * Recursively discover flattened fields in maps for `#[serde(flatten)]`. (https://github.com/juhaku/utoipa/pull/1582) --- utoipa-gen/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index b86d4bf4..5d104d07 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -27,6 +27,7 @@ ### 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) From 1436f789a0ec3f18ad422efca4027938673bb0f6 Mon Sep 17 00:00:00 2001 From: Tom <1955774+tdelmas@users.noreply.github.com> Date: Thu, 3 Sep 2026 21:31:10 +0200 Subject: [PATCH 12/26] Bump base64 from 22.1 to 23.1 (#1595) --- utoipa-swagger-ui/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utoipa-swagger-ui/Cargo.toml b/utoipa-swagger-ui/Cargo.toml index bb51e645..07a78a89 100644 --- a/utoipa-swagger-ui/Cargo.toml +++ b/utoipa-swagger-ui/Cargo.toml @@ -40,7 +40,7 @@ utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, feat ] } 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" From fbe663958f6a5b834b1fb7c15bbc6fabe4722b40 Mon Sep 17 00:00:00 2001 From: Jakob Hellermann Date: Thu, 3 Sep 2026 22:18:03 +0200 Subject: [PATCH 13/26] Upgrade utoipa-gen to syn 3 (#1597) --- utoipa-gen/Cargo.toml | 2 +- utoipa-gen/src/path.rs | 11 ++++------- utoipa-gen/src/path/response/derive.rs | 6 +++++- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/utoipa-gen/Cargo.toml b/utoipa-gen/Cargo.toml index ebf45410..c12c6283 100644 --- a/utoipa-gen/Cargo.toml +++ b/utoipa-gen/Cargo.toml @@ -25,7 +25,7 @@ proc-macro = true 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 } diff --git a/utoipa-gen/src/path.rs b/utoipa-gen/src/path.rs index 04d79af0..9de65ad4 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/response/derive.rs b/utoipa-gen/src/path/response/derive.rs index f0e3df72..76005ab6 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) } From 0f601fef4b72f114be3a4fe97943022bfe171003 Mon Sep 17 00:00:00 2001 From: Til Blechschmidt Date: Wed, 16 Sep 2026 13:32:35 +0200 Subject: [PATCH 14/26] feature: support extensions in utoipa::ToSchema named structs (#1593) --- utoipa-gen/CHANGELOG.md | 1 + utoipa-gen/src/component/schema/features.rs | 9 +++++---- utoipa-gen/src/lib.rs | 14 ++++++++++++++ utoipa-gen/tests/schema_derive_test.rs | 21 +++++++++++++++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 5d104d07..94da537f 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -17,6 +17,7 @@ * 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 diff --git a/utoipa-gen/src/component/schema/features.rs b/utoipa-gen/src/component/schema/features.rs index f73601e7..1fe4f7c1 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/lib.rs b/utoipa-gen/src/lib.rs index 576f92f9..2b8f3ebd 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -204,6 +204,7 @@ static CONFIG: once_cell::sync::Lazy = /// * `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 diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 710434c0..dee1ff58 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -192,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! { From 69af0403df8ee5ac00fc530f0fbac32348a39ada Mon Sep 17 00:00:00 2001 From: Mattias Eriksson <6420639+snaggen@users.noreply.github.com> Date: Wed, 16 Sep 2026 14:39:51 +0200 Subject: [PATCH 15/26] Re-enable actix auto_into_responses Result test (#1603) The test was commented out as failing to compile. It was missing imports, and the justfile did not enable `utoipa/auto_into_responses`, which gates the `IntoResponses` impl for `Result`. --- justfile | 2 +- .../path_derive_auto_into_responses_actix.rs | 128 +++++++++--------- ...__path_operation_auto_types_responses.snap | 22 +++ 3 files changed, 87 insertions(+), 65 deletions(-) create mode 100644 utoipa-gen/tests/snapshots/path_derive_auto_into_responses_actix__path_operation_auto_types_responses.snap diff --git a/justfile b/justfile index 48321eb5..e4ad913b 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 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 f334048b..9ffb6694 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/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 00000000..a7c3f01c --- /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" + } +} From 14e2a905331af18cc5387900e3136aa6eba7e0c1 Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Wed, 23 Sep 2026 01:13:56 +0300 Subject: [PATCH 16/26] Update next release versions (#1618) --- README.md | 2 +- utoipa-actix-web/CHANGELOG.md | 6 ++++++ utoipa-actix-web/Cargo.toml | 6 +++--- utoipa-actix-web/README.md | 2 +- utoipa-actix-web/src/lib.rs | 2 +- utoipa-axum/CHANGELOG.md | 3 ++- utoipa-axum/Cargo.toml | 4 ++-- utoipa-axum/README.md | 2 +- utoipa-axum/src/lib.rs | 2 +- utoipa-config/CHANGELOG.md | 11 ++++++++++- utoipa-config/Cargo.toml | 2 +- utoipa-config/config-test-crate/Cargo.toml | 2 +- utoipa-gen/CHANGELOG.md | 3 ++- utoipa-gen/Cargo.toml | 2 +- utoipa-rapidoc/CHANGELOG.md | 5 +++++ utoipa-rapidoc/Cargo.toml | 4 ++-- utoipa-rapidoc/README.md | 4 ++-- utoipa-rapidoc/src/lib.rs | 4 ++-- utoipa-redoc/CHANGELOG.md | 5 +++++ utoipa-redoc/Cargo.toml | 4 ++-- utoipa-redoc/README.md | 4 ++-- utoipa-redoc/src/lib.rs | 4 ++-- utoipa-scalar/CHANGELOG.md | 7 ++++++- utoipa-scalar/Cargo.toml | 4 ++-- utoipa-scalar/README.md | 4 ++-- utoipa-scalar/src/lib.rs | 4 ++-- utoipa-swagger-ui-vendored/CHANGELOG.md | 4 +++- utoipa-swagger-ui-vendored/Cargo.toml | 2 +- utoipa-swagger-ui/CHANGELOG.md | 3 ++- utoipa-swagger-ui/Cargo.toml | 6 +++--- utoipa-swagger-ui/README.md | 4 ++-- utoipa-swagger-ui/src/lib.rs | 4 ++-- utoipa/CHANGELOG.md | 3 ++- utoipa/Cargo.toml | 4 ++-- utoipa/src/lib.rs | 2 +- 35 files changed, 85 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 8a5666db..6a721291 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Add dependency declaration to `Cargo.toml`. ```toml [dependencies] -utoipa = "5" +utoipa = "6" ``` ## Examples diff --git a/utoipa-actix-web/CHANGELOG.md b/utoipa-actix-web/CHANGELOG.md index 2572d68e..200aea1f 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 92f02e64..88c91276 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 = { path = "../utoipa", version = "5" } +utoipa = { path = "../utoipa", version = "6" } actix-web = { version = "4", default-features = false } actix-service = "2" [dev-dependencies] -utoipa = { path = "../utoipa", version = "5", features = [ +utoipa = { path = "../utoipa", features = [ "actix_extras", "macros", "debug", diff --git a/utoipa-actix-web/README.md b/utoipa-actix-web/README.md index 594bfa71..e937ed7f 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 1dedaa59..12cd6ce0 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-axum/CHANGELOG.md b/utoipa-axum/CHANGELOG.md index 63ce7d03..9a5e4e31 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 0d585e4f..cd1a90db 100644 --- a/utoipa-axum/Cargo.toml +++ b/utoipa-axum/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-axum" description = "Utoipa's axum bindings for seamless integration for the two" -version = "0.2.0" +version = "0.3.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -23,7 +23,7 @@ debug = [] [dependencies] axum = { version = "0.8.4", default-features = false } -utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } tower-service = "0.3" diff --git a/utoipa-axum/README.md b/utoipa-axum/README.md index 522d6d21..843e5850 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 e36562b4..7377b358 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 diff --git a/utoipa-config/CHANGELOG.md b/utoipa-config/CHANGELOG.md index 67d9b040..2fa04a86 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 4d8f3814..fb2197ed 100644 --- a/utoipa-config/Cargo.toml +++ b/utoipa-config/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-config" description = "Config for controlling utoipa's various aspects" -version = "0.1.2" +version = "0.1.3" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" diff --git a/utoipa-config/config-test-crate/Cargo.toml b/utoipa-config/config-test-crate/Cargo.toml index ae608f77..cb7d93ae 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 = { version = "5.0.0", path = "../../utoipa", features = [ +utoipa = { version = "6.0.0", path = "../../utoipa", features = [ "debug", "config", ] } diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 94da537f..dc758620 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog - utoipa-gen -## Unreleased +## 6.0.0 - Sep 23 2026 ### Added @@ -21,6 +21,7 @@ ### Changed +* 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) diff --git a/utoipa-gen/Cargo.toml b/utoipa-gen/Cargo.toml index c12c6283..86fe958e 100644 --- a/utoipa-gen/Cargo.toml +++ b/utoipa-gen/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-gen" description = "Code generation implementation for utoipa" -version = "5.5.0" +version = "6.0.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" diff --git a/utoipa-rapidoc/CHANGELOG.md b/utoipa-rapidoc/CHANGELOG.md index c9b3b169..7ab28f2a 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 33739157..a5698396 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"] @@ -22,7 +22,7 @@ rocket = ["dep:rocket", "dep:time"] [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } -utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } actix-web = { version = "4", optional = true, default-features = false } diff --git a/utoipa-rapidoc/README.md b/utoipa-rapidoc/README.md index 6fc3a481..d0c090e5 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 2459e2ca..df508580 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 50929ce5..63c79149 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 b7ab9d43..9e01c62d 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" @@ -22,7 +22,7 @@ rocket = ["dep:rocket", "dep:time"] [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } -utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } actix-web = { version = "4", optional = true } diff --git a/utoipa-redoc/README.md b/utoipa-redoc/README.md index 845c66a1..d5ef6f4f 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 e4063aab..51311999 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 c4d3e59b..f7f0cd94 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 d0355493..fd5e05ed 100644 --- a/utoipa-scalar/Cargo.toml +++ b/utoipa-scalar/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-scalar" description = "Scalar for utoipa" -version = "0.3.0" +version = "0.4.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -22,7 +22,7 @@ rocket = ["dep:rocket", "dep:time"] [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } -utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } actix-web = { version = "4", optional = true, default-features = false } diff --git a/utoipa-scalar/README.md b/utoipa-scalar/README.md index 6e3b5c74..bc3bd5f9 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 fb6c3062..a6681068 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 4475f6f2..b8ad8058 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 c23e8c2f..bb2cc1a4 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" diff --git a/utoipa-swagger-ui/CHANGELOG.md b/utoipa-swagger-ui/CHANGELOG.md index 03e933e7..7aee4944 100644 --- a/utoipa-swagger-ui/CHANGELOG.md +++ b/utoipa-swagger-ui/CHANGELOG.md @@ -1,9 +1,10 @@ # Changelog - utoipa-swagger-ui -## Unreleased +## 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 07a78a89..35856ddb 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.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -35,7 +35,7 @@ time = { workspace = true, optional = true } axum = { version = "0.8.4", default-features = false, features = [ "json", ], optional = true } -utoipa = { version = "5.0.0", path = "../utoipa", default-features = false, features = [ +utoipa = { version = "6.0.0", path = "../utoipa", default-features = false, features = [ "macros", ] } serde = { version = "1.0", features = ["derive", "rc"] } @@ -70,7 +70,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] workspace = true diff --git a/utoipa-swagger-ui/README.md b/utoipa-swagger-ui/README.md index 84d06b4c..f143d447 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/src/lib.rs b/utoipa-swagger-ui/src/lib.rs index ea71c29a..1984e715 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 03dc2b76..4dc0a0f6 100644 --- a/utoipa/CHANGELOG.md +++ b/utoipa/CHANGELOG.md @@ -3,7 +3,7 @@ **`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 +## 6.0.0 - Sep 23 2026 ### Added @@ -20,6 +20,7 @@ to look into changes introduced to **`utoipa-gen`**. ### Changed +* 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 e0d1f591..9bc591bf 100644 --- a/utoipa/Cargo.toml +++ b/utoipa/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa" description = "Compile time generated OpenAPI documentation for Rust" -version = "5.5.0" +version = "6.0.0" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -63,7 +63,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 = { version = "5.5.0", path = "../utoipa-gen", optional = true } +utoipa-gen = { version = "6.0.0", path = "../utoipa-gen", optional = true } indexmap = { version = "2", features = ["serde"] } [dev-dependencies] diff --git a/utoipa/src/lib.rs b/utoipa/src/lib.rs index ae773866..19f91b11 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 From baa4d04c78fdcc86622e1a2775039fc1621157c0 Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Wed, 23 Sep 2026 01:24:36 +0300 Subject: [PATCH 17/26] Remove support for expression ignore in `ToSchema` and `IntoParams` (#1619) This commit removes support for expression style ignore attribute from `ToSchema` and `IntoParams` macro. This is to fix issue where ignore sometimes did not ignore values, because it was evaluated in runtime and function reference ignore can be evaluated only during runtime but we need to evaluate this at build time thus removing the possibility to define function reference as ignore attribute value. ## Breaking Following syntax demonstrates what was allowed before, but will be not available in new version 6. ```rust // before allowed fn ignore_always() -> bool { true } #[derive(ToSchema)] struct Value { #[schema(ignore = ignore_always)] field: String } ``` --- utoipa-gen/CHANGELOG.md | 1 + .../src/component/features/attributes.rs | 12 +++-- utoipa-gen/src/component/into_params.rs | 18 +------- utoipa-gen/src/component/schema.rs | 18 ++------ utoipa-gen/src/lib.rs | 16 ++----- utoipa-gen/tests/path_derive.rs | 35 --------------- utoipa-gen/tests/schema_derive_test.rs | 45 ------------------- utoipa/CHANGELOG.md | 1 + utoipa/src/lib.rs | 7 --- 9 files changed, 19 insertions(+), 134 deletions(-) diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index dc758620..41cf3860 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -21,6 +21,7 @@ ### 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) diff --git a/utoipa-gen/src/component/features/attributes.rs b/utoipa-gen/src/component/features/attributes.rs index 15ce091c..3f0adda0 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}; @@ -995,7 +995,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 { @@ -1003,7 +1003,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()) + } } } @@ -1021,7 +1025,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 61c9abb8..4ad0a0e6 100644 --- a/utoipa-gen/src/component/into_params.rs +++ b/utoipa-gen/src/component/into_params.rs @@ -25,7 +25,6 @@ use crate::{ FieldRename, }, doc_comment::CommentAttributes, - parse_utils::LitBoolOrExprPath, token_stream::{quote_diagnostics, Diagnostics, ToTokensDiagnostics}, OptionExt, Required, }; @@ -361,7 +360,7 @@ impl Param { .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 }, @@ -450,7 +449,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 @@ -459,19 +458,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 4d393332..d0064698 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 { @@ -459,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/lib.rs b/utoipa-gen/src/lib.rs index 2b8f3ebd..58b2eec3 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -162,7 +162,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,8 +199,7 @@ 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**. @@ -2408,8 +2407,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 /// @@ -3740,12 +3738,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/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index 3e5e82a9..f699cb6c 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -1938,41 +1938,6 @@ fn derive_into_params_with_ignored_enum_field() { assert_json_snapshot!(value); } -#[test] -fn derive_into_params_with_ignored_struct_fn_field() { - #![allow(unused)] - - fn always_true() -> bool { - true - }; - - #[derive(ToSchema)] - struct PrivateOrPublic { - name: &'static str, - } - - #[derive(IntoParams)] - #[into_params(parameter_in = Query)] - struct Params { - value: String, - #[param(ignore = always_true)] - private_or_public: PrivateOrPublic, - } - - #[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_generic_field() { #[derive(ToSchema)] diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index dee1ff58..7e365965 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -3209,27 +3209,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)] @@ -3264,30 +3243,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)] diff --git a/utoipa/CHANGELOG.md b/utoipa/CHANGELOG.md index 4dc0a0f6..e8a7090f 100644 --- a/utoipa/CHANGELOG.md +++ b/utoipa/CHANGELOG.md @@ -20,6 +20,7 @@ to look into changes introduced to **`utoipa-gen`**. ### 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) diff --git a/utoipa/src/lib.rs b/utoipa/src/lib.rs index 19f91b11..b679dcd0 100644 --- a/utoipa/src/lib.rs +++ b/utoipa/src/lib.rs @@ -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)] From 7ebfd239523f41cd82e26e3bc7b796cfba78ec1d Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Wed, 23 Sep 2026 18:18:50 +0300 Subject: [PATCH 18/26] Fix publish crate version bash substitution pattern --- .github/actions/publish/publish.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/publish/publish.sh b/.github/actions/publish/publish.sh index ab9d7b41..59bc69e7 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 From e1d896448a5e5ca9fb7b69deedd02f7b00394154 Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Wed, 23 Sep 2026 18:48:50 +0300 Subject: [PATCH 19/26] Fix min properties schema generation (#1623) This bug has been around since `utoipa-gen 5.1.3` where the `#[schema(min_properties=...)]` gets generated as `max_properties` attribute. Closes #1622 --- utoipa-gen/CHANGELOG.md | 6 +++++ utoipa-gen/Cargo.toml | 2 +- utoipa-gen/src/component/features.rs | 2 +- utoipa-gen/tests/schema_derive_test.rs | 13 +++++++++++ ...rive_correct_exclusive_min_properties.snap | 22 +++++++++++++++++++ 5 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 utoipa-gen/tests/snapshots/schema_derive_test__derive_correct_exclusive_min_properties.snap diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 41cf3860..ffc3ab06 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog - utoipa-gen +## 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 diff --git a/utoipa-gen/Cargo.toml b/utoipa-gen/Cargo.toml index 86fe958e..9fcbdbb0 100644 --- a/utoipa-gen/Cargo.toml +++ b/utoipa-gen/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "utoipa-gen" description = "Code generation implementation for utoipa" -version = "6.0.0" +version = "6.0.1" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" diff --git a/utoipa-gen/src/component/features.rs b/utoipa-gen/src/component/features.rs index 8a0e4ec4..3f316911 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/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 7e365965..76e2e1ae 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -3688,3 +3688,16 @@ fn derive_schema_with_many_fields_compiles() { 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); +} 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 00000000..d20f7ec3 --- /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" +} From 4225d2ebefa86696affc69fdd5b38a8c38cb3eca Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Thu, 24 Sep 2026 02:05:52 +0300 Subject: [PATCH 20/26] Fix utoipa-swagger-ui build (#1624) Utoipa-swagger-ui build failed to build with `cache` feature on because sha2 crate had updated its `generic-array` to `hybrid-array` dependency breaking the existing implementation hex formatting. More details here: https://github.com/RustCrypto/hybrid-array/issues/201 --- justfile | 2 +- utoipa-swagger-ui/CHANGELOG.md | 6 ++++++ utoipa-swagger-ui/Cargo.toml | 9 +++++---- utoipa-swagger-ui/build.rs | 8 +++++--- 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/justfile b/justfile index e4ad913b..98438c79 100644 --- a/justfile +++ b/justfile @@ -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-swagger-ui/CHANGELOG.md b/utoipa-swagger-ui/CHANGELOG.md index 7aee4944..b5bc0382 100644 --- a/utoipa-swagger-ui/CHANGELOG.md +++ b/utoipa-swagger-ui/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog - utoipa-swagger-ui +## 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 diff --git a/utoipa-swagger-ui/Cargo.toml b/utoipa-swagger-ui/Cargo.toml index 35856ddb..eb60551d 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 = "10.0.0" +version = "10.0.1" edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" @@ -18,7 +18,7 @@ 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+. @@ -50,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"] @@ -60,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. diff --git a/utoipa-swagger-ui/build.rs b/utoipa-swagger-ui/build.rs index 11938caa..4da1c91b 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} }}"### ) From 186da6cdf65a757720f96f201b42eb9763a4b14e Mon Sep 17 00:00:00 2001 From: Mukunda Rao Katta Date: Thu, 24 Sep 2026 15:23:11 -0700 Subject: [PATCH 21/26] Fix unsigned integer known format serialization (#1554) Fix unsigned integers know format serialization. They used falsely `kebab-case` instead of `lowercase`. Now type like `UInt16` will render `uint16` instead of `u-int16`. --------- Co-authored-by: Juha Kukkonen --- utoipa/CHANGELOG.md | 6 ++++++ utoipa/src/lib.rs | 4 ++-- utoipa/src/openapi/schema.rs | 25 +++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/utoipa/CHANGELOG.md b/utoipa/CHANGELOG.md index e8a7090f..70bcf619 100644 --- a/utoipa/CHANGELOG.md +++ b/utoipa/CHANGELOG.md @@ -3,6 +3,12 @@ **`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 + +### Fixed + +* Fix unsigned integer known format serialization (https://github.com/juhaku/utoipa/pull/1554) + ## 6.0.0 - Sep 23 2026 ### Added diff --git a/utoipa/src/lib.rs b/utoipa/src/lib.rs index b679dcd0..36187aad 100644 --- a/utoipa/src/lib.rs +++ b/utoipa/src/lib.rs @@ -1633,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/schema.rs b/utoipa/src/openapi/schema.rs index 29bb832f..7c491b3f 100644 --- a/utoipa/src/openapi/schema.rs +++ b/utoipa/src/openapi/schema.rs @@ -2380,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, @@ -2480,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() From 65d523269106dbd3c3f76781fdcc1e0cf9750d06 Mon Sep 17 00:00:00 2001 From: Omid Rad Date: Fri, 25 Sep 2026 01:34:29 +0200 Subject: [PATCH 22/26] Accept `expr` for attr for `title` and `names` (#1524) Implements rust expression support for `names` and `title` attributes: ```rust const STRUCT_TITLE: &str = "Post Title"; let schema = api_doc! { #[schema(title = STRUCT_TITLE)] struct Post { id: i64, description: String, } }; const NEW_NAME: &str = "renamed_field"; #[derive(IntoParams)] #[into_params(parameter_in = Path, names(NEW_NAME))] struct Filter( #[allow(unused)] (), ); ``` --------- Co-authored-by: Juha Kukkonen --- utoipa-gen/CHANGELOG.md | 6 ++ .../src/component/features/attributes.rs | 14 ++-- utoipa-gen/src/component/into_params.rs | 33 +++++--- utoipa-gen/src/lib.rs | 8 +- utoipa-gen/tests/path_derive.rs | 81 +++++++++++++++++-- utoipa-gen/tests/schema_derive_test.rs | 15 ++++ 6 files changed, 131 insertions(+), 26 deletions(-) diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index ffc3ab06..307319ea 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog - utoipa-gen +## Unreleased + +### Added + +* Add support for expression for `title` and `names` (https://github.com/juhaku/utoipa/pull/1524) + ## 6.0.1 - Sep 23 2026 ### Fixed diff --git a/utoipa-gen/src/component/features/attributes.rs b/utoipa-gen/src/component/features/attributes.rs index 3f0adda0..e62c77dd 100644 --- a/utoipa-gen/src/component/features/attributes.rs +++ b/utoipa-gen/src/component/features/attributes.rs @@ -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(), )) } diff --git a/utoipa-gen/src/component/into_params.rs b/utoipa-gen/src/component/into_params.rs index 4ad0a0e6..cfce72b0 100644 --- a/utoipa-gen/src/component/into_params.rs +++ b/utoipa-gen/src/component/into_params.rs @@ -25,6 +25,7 @@ use crate::{ FieldRename, }, doc_comment::CommentAttributes, + parse_utils::LitStrOrExpr, token_stream::{quote_diagnostics, Diagnostics, ToTokensDiagnostics}, OptionExt, Required, }; @@ -204,7 +205,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 { @@ -239,7 +240,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 { @@ -278,7 +279,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. @@ -342,19 +343,15 @@ 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)?; @@ -376,8 +373,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() diff --git a/utoipa-gen/src/lib.rs b/utoipa-gen/src/lib.rs index 58b2eec3..0610093a 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -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. @@ -2304,7 +2305,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 diff --git a/utoipa-gen/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index f699cb6c..3a4b0bba 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -911,6 +911,77 @@ 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( @@ -1570,13 +1641,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" diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 76e2e1ae..47ada3b7 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -3701,3 +3701,18 @@ fn derive_correct_exclusive_min_properties() { 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); +} From 26e67131a24e3fb9e5172660259ab4bc72989e51 Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Fri, 25 Sep 2026 02:42:02 +0300 Subject: [PATCH 23/26] Fix format --- utoipa-gen/tests/path_derive.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/utoipa-gen/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index 3a4b0bba..9fa9c737 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -917,10 +917,7 @@ fn derive_parameter_rename_expr() { #[derive(IntoParams)] #[into_params(parameter_in = Path, names(NEW_NAME))] - struct Filter( - #[allow(unused)] - (), - ); + struct Filter(#[allow(unused)] ()); #[utoipa::path( get, @@ -952,12 +949,7 @@ fn derive_parameter_rename_expr_in_param_name_and_title() { #[derive(IntoParams)] #[into_params(parameter_in = Query, names(PARAM_NAME, PARAM_TITLE))] - struct Filter( - #[allow(unused)] - String, - #[allow(unused)] - String, - ); + struct Filter(#[allow(unused)] String, #[allow(unused)] String); #[utoipa::path( get, From 2dfe23dc6ecf0c0952c1863b8c3546b8bbaad967 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Fri, 25 Sep 2026 10:24:56 +0300 Subject: [PATCH 24/26] Add missing utoipa-gen snapshots for rename-expression derives (#1625) Add missing snapshots for `utoipa-gen` test using newly supported expression in title and name. ```rust const NEW_NAME: &str = "renamed_field"; #[derive(IntoParams)] #[into_params(parameter_in = Path, names(NEW_NAME))] struct Filter(()); ``` --------- Co-authored-by: juhaku <26358664+juhaku@users.noreply.github.com> --- ..._derive__derive_parameter_rename_expr.snap | 14 ++++++++++++ ...r_rename_expr_in_param_name_and_title.snap | 22 +++++++++++++++++++ ..._derive_struct_with_field_rename_expr.snap | 21 ++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr.snap create mode 100644 utoipa-gen/tests/snapshots/path_derive__derive_parameter_rename_expr_in_param_name_and_title.snap create mode 100644 utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_with_field_rename_expr.snap 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 00000000..209979ab --- /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 00000000..a12eb12c --- /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/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 00000000..b2855936 --- /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" +} From a32c8e60bbb674392bc48428c5b712391832f09a Mon Sep 17 00:00:00 2001 From: Max Azatian <66359507+HardMax71@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:42:42 +0200 Subject: [PATCH 25/26] Mark Option fields with deserialize_with as required (#1627) Serde only treats a missing Option field as None when the field has no deserialize_with or with attribute. With one of those and no default, a missing field is an error, so ToSchema and IntoParams should list the field as required. It stays nullable. --- utoipa-gen/CHANGELOG.md | 4 +++ utoipa-gen/src/component.rs | 3 ++ utoipa-gen/src/component/into_params.rs | 5 ++-- utoipa-gen/src/component/schema.rs | 4 +-- utoipa-gen/src/component/serde.rs | 8 +++++ utoipa-gen/tests/path_derive.rs | 29 ++++++++++++++++++ utoipa-gen/tests/schema_derive_test.rs | 18 +++++++++++ ...ion_with_deserialize_with_is_required.snap | 30 +++++++++++++++++++ ...ion_with_deserialize_with_is_required.snap | 30 +++++++++++++++++++ 9 files changed, 127 insertions(+), 4 deletions(-) create mode 100644 utoipa-gen/tests/snapshots/path_derive__derive_into_params_option_with_deserialize_with_is_required.snap create mode 100644 utoipa-gen/tests/snapshots/schema_derive_test__derive_struct_option_with_deserialize_with_is_required.snap diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index 307319ea..ef758a06 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -6,6 +6,10 @@ * Add support for expression for `title` and `names` (https://github.com/juhaku/utoipa/pull/1524) +### 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 diff --git a/utoipa-gen/src/component.rs b/utoipa-gen/src/component.rs index e102e653..1913c602 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 diff --git a/utoipa-gen/src/component/into_params.rs b/utoipa-gen/src/component/into_params.rs index cfce72b0..95bec7e4 100644 --- a/utoipa-gen/src/component/into_params.rs +++ b/utoipa-gen/src/component/into_params.rs @@ -429,8 +429,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()), diff --git a/utoipa-gen/src/component/schema.rs b/utoipa-gen/src/component/schema.rs index d0064698..03c870bb 100644 --- a/utoipa-gen/src/component/schema.rs +++ b/utoipa-gen/src/component/schema.rs @@ -444,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, diff --git a/utoipa-gen/src/component/serde.rs b/utoipa-gen/src/component/serde.rs index e20c6136..294b168e 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/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index 9fa9c737..ecec876d 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -1206,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)] diff --git a/utoipa-gen/tests/schema_derive_test.rs b/utoipa-gen/tests/schema_derive_test.rs index 47ada3b7..1f578d27 100644 --- a/utoipa-gen/tests/schema_derive_test.rs +++ b/utoipa-gen/tests/schema_derive_test.rs @@ -1598,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)] 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 00000000..6af4fab6 --- /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/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 00000000..853f09ab --- /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" +} From 2ec67b85677e05e492aa77e53c57fb3fe3dfc217 Mon Sep 17 00:00:00 2001 From: Juha Kukkonen Date: Mon, 28 Sep 2026 17:55:49 +0300 Subject: [PATCH 26/26] Support `merge` in `OpenApi` derive (#1628) Add support for `merge` in `OpenApi` derive Keep nest and merge as separate derive attributes, but parse their common api and tags arguments through OpenApiReference. List merge in the unexpected-attribute diagnostic and cover merge precedence in tests. --------- Co-authored-by: Martin Moreira de Jesus --- utoipa-gen/CHANGELOG.md | 2 +- utoipa-gen/src/lib.rs | 44 +++ utoipa-gen/src/openapi.rs | 250 +++++++++++++----- utoipa-gen/tests/openapi_derive.rs | 182 +++++++++++++ ...isting_items_and_appends_missing_ones.snap | 124 +++++++++ ...erive__derive_merge_openapi_with_tags.snap | 31 +++ 6 files changed, 567 insertions(+), 66 deletions(-) create mode 100644 utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_keeps_existing_items_and_appends_missing_ones.snap create mode 100644 utoipa-gen/tests/snapshots/openapi_derive__derive_merge_openapi_with_tags.snap diff --git a/utoipa-gen/CHANGELOG.md b/utoipa-gen/CHANGELOG.md index ef758a06..2273a50b 100644 --- a/utoipa-gen/CHANGELOG.md +++ b/utoipa-gen/CHANGELOG.md @@ -5,6 +5,7 @@ ### 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 @@ -65,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/src/lib.rs b/utoipa-gen/src/lib.rs index 0610093a..0965dfdc 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -2034,6 +2034,11 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// * `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 @@ -2108,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.**_ @@ -2245,6 +2263,32 @@ 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 diff --git a/utoipa-gen/src/openapi.rs b/utoipa-gen/src/openapi.rs index 5a9d48db..999e8827 100644 --- a/utoipa-gen/src/openapi.rs +++ b/utoipa-gen/src/openapi.rs @@ -40,6 +40,7 @@ pub struct OpenApiAttr<'o> { external_docs: Option, servers: Punctuated, nested: Vec, + merged: Vec, } impl<'o> OpenApiAttr<'o> { @@ -71,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 } @@ -88,7 +91,8 @@ pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Result 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, version"; + "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() { @@ -139,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)); } @@ -360,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 @@ -409,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<'_> { @@ -508,6 +512,11 @@ 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 { @@ -527,6 +536,7 @@ impl ToTokensDiagnostics for OpenApi<'_> { #handler_schemas components.schemas.extend(schemas); #nested_tokens + #merged_tokens #modifiers_tokens @@ -727,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/tests/openapi_derive.rs b/utoipa-gen/tests/openapi_derive.rs index c2a7b9d2..7a059f1e 100644 --- a/utoipa-gen/tests/openapi_derive.rs +++ b/utoipa-gen/tests/openapi_derive.rs @@ -417,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/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 00000000..086963cf --- /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", + "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 00000000..cd653f7f --- /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" + ] + } + } +}