Reasons why discriminator syntax only works with #[serde(untagged)]
variables
#1227
-
I was wondering why the new discriminator syntax only works for serde untagged enums. For a project I'm working on we'd like to use the discriminator syntax for all generated enums because the downstream generators we use have better support for it. Just to test if this work locally, I created a fork where I removed the clause specifying that for usage with the discriminator syntax you'll need #![expect(dead_code)]
use serde::Deserialize;
use utoipa::{OpenApi, ToSchema};
#[derive(Debug, Deserialize, ToSchema)]
struct Document {
content: DocumentKind,
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(tag = "kind")]
#[schema(discriminator(property_name = "kind", mapping(
("Person" = "#/components/schemas/Person"),
("Machine" = "#/components/schemas/Machine"),
)))]
enum DocumentKind {
Person(Person),
Machine(Machine),
}
#[derive(Debug, Deserialize, ToSchema)]
struct Person {
name: String,
}
#[derive(Debug, Deserialize, ToSchema)]
struct Machine {
identifier: String,
}
#[derive(OpenApi)]
#[openapi(components(schemas(Document, DocumentKind, Person, Machine)))]
struct ApiDocs;
fn main() {
let json = ApiDocs::openapi()
.to_json()
.expect("Could not create api spec");
println!("{json}");
} And below my generated openapi spec: If there is no real reason why this is not supported, I'd love to make a pr. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The reason can be summarized to this #621, #617 and #346. And it relates to this issue OpenAPITools/openapi-generator#1086. In short the discriminator should only be used with
However as I see this mention has been removed from the latest spec 3.1.1 version so there might be some changes towards supporting this functionality officially. I am not tracking changes what's coming into the OpenAPI in general. Perhaps it would be good to use some tool to lint the generated OpenAPI and see whether it produces any errors. |
Beta Was this translation helpful? Give feedback.
The reason can be summarized to this #621, #617 and #346. And it relates to this issue OpenAPITools/openapi-generator#1086. In short the discriminator should only be used with
$ref
fields and not with schema combining$ref
and inlined objects according to 3.1.0 version of spec https://spec.openapis.org/oas/v3.1.0.html#discriminator-object.However as I see this mention has been removed from the latest spec 3.1.1 version so there might be some changes towards supporting this functionality officially. I am not tracking changes what's coming into the OpenAPI in general.
Perhaps it would be good to use some tool to lint th…