juhaku / utoipa

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

ToSchema derives array with items with allOf combination of the types of all the tuple elements #901

Open taladar opened 1 month ago

taladar commented 1 month ago

Given e.g.

use utoipa::{OpenApi, ToSchema};

#[derive(ToSchema)]
struct A((Option<String>, String));

#[derive(OpenApi)]
#[openapi(components(schemas(A)))]
struct Api;

fn main() {
    println!("{}", Api::openapi().to_pretty_json().unwrap())
}

we get

{
  "openapi": "3.0.3",
  "info": {
    "title": "utoipa-test",
    "description": "",
    "license": {
      "name": ""
    },
    "version": "0.1.0"
  },
  "paths": {},
  "components": {
    "schemas": {
      "A": {
        "type": "array",
        "items": {
          "allOf": [
            {
              "type": "string",
              "nullable": true
            },
            {
              "type": "string"
            }
          ]
        }
      }
    }
  }
}

which seems to be the schema for a type that fulfills all the requirements at the same time instead of one where each element fulfills one of the requirements.

This happens for both enum and struct fields and it does not seem to matter if the field is named which leads me to conclude that the location of the tuple within the type we derive ToSchema on probably doesn't matter.

taladar commented 1 month ago

Tuples don't seem to be supported exactly in OpenAPI but it would probably be possible to at least use anyOf and minItems and maxItems to get as close as OpenAPI allows the validation to go.

Alternatively if someone uses a tuple and it is not supported by utoipa at all it should probably lead to a compile error.