juhaku / utoipa

Simple, Fast, Code first and Compile time generated OpenAPI documentation for Rust
Apache License 2.0
2.5k stars 197 forks source link

Support for generic data structures in OAS 3.1 #1148

Open ranger-ross opened 1 month ago

ranger-ross commented 1 month ago

Hey there :wave:

Now that Utoipa 5 has landed with OAS 3.1 support, a useful feature would Generic Data Structures using JSON Schema's dynamic referencing feature ($dynamicRef and $dynamicAnchor)

This is a usecase that is explicitly being mention in the upcoming 3.1.1 and 3.2.0 OAS drafts, but is available in 3.1.0 already.


Currently if I had the following:

#[derive(ToSchema, Debug, Serialize)]
struct Foo {
    name: String,
}

#[derive(ToSchema, Serialize)]
struct Wrapper<T: Serialize> {
    status: String,
    data: Option<T>,
}

// actix handler
#[utoipa::path(responses((status = 200, body = Wrapper<Foo>)))]
#[get("/")]
async fn hello() -> impl Responder {
   todo!()
}

The Wrapper type gets appended to Foo like so

image

This works but its a bit unfortunate for as is makes the client generated code messy. :crying_cat_face: Adding support for generic data structure templates would make it possible for client generators to generated generic code on the client side as well. (assuming the language of the client support generics of course)

Also I am not sure how many generators support this yet, so I would assume it would be best to add this behind a crate feature flag that is opt in to avoid breaking lots of ppl :thinking:

juhaku commented 1 month ago

Right, sure definitely under some feature flag that can be optionally enabled. This probably needs some assessment how it can be supported in utoipa and some experimenting around it.

This somehow sounds like undoing some of the new generic logic like now it inlines the schemas by creating Wrapper_Foo but then instead of inlining it should create a $dynamicRef or something.