getkin / kin-openapi

OpenAPI 3.0 (and Swagger v2) implementation for Go (parsing, converting, validation, and more)
MIT License
2.63k stars 432 forks source link

Validation issues with schema examples #995

Open juicyarts opened 4 months ago

juicyarts commented 4 months ago

Hey folks,

I'm trying to wrap my head around how schema examples work in kin and am encountering issues no matter how i approach it..

For example, If i try to pass an instance of the underlying object:

package api

...
type Foo struct {
  Bar bool `json:"bar"`
}
...

ex := Foo{Bar: true}
schema.Example = &ex 

i get

failed validation: invalid components: schema "Foo": invalid example: unhandled value of type *api.Foo
Schema:
  {
    "example": {
      "bar": true
    },
    "properties": {
      "bar": {
        "type": "boolean"
      }
    },
    "required": [
      "bar"
    ],
    "type": "object"
  }

Value:
  {
    "bar": true
  }

If i try to pass an instance of openapi3.Example:

...
schema.Example = openapi3.Example{
    Description: "TEst",
    Value: &ex,
}
...

i get

failed validation: invalid components: schema "Foo": invalid example: unhandled value of type openapi3.Example
Schema:
  {
    "example": {
      "description": "TEst",
      "value": {
        "bar": true
      }
    },
    "properties": {
      "bar": {
        "type": "boolean"
      }
    },
    "required": [
      "bar"
    ],
    "type": "object"
  }

Value:
  {
    "description": "TEst",
    "value": {
      "bar": true
    }
  }

How do i provide examples for a schema properly here? I think i scanned all documentation i could find, and am still clueless..

I'm using a fork of a-h/rest here, but this is definitely an issue thrown by kin-openapi3, which is why i can't provide a full reproduction of the issue right now. Maybe you can help me nonetheless? Like is there a thorough example of how to use schema examples anywhere, Not having any type information here makes this really hard to grasp. Only way to suppress these warnings is disabling example validation, which is not really satisfying.
If necessary i can try to build a full example to reproduce the problem in the next days.

Thanks for your work!

juicyarts commented 3 months ago

I was able to figure out how this works, so for those who might be interested:

Schema.Example expects either a single primitive type value s.Example = true, s.Example = "foO", s.Example = 1, ..., a slice of type any, or a map[string|any]any and is not capable of handling structs directly or any other datatype not defined in here.

For the examples above this means:


// The type that the schema's properties are based on
type Foo struct {
  Bar bool `json:"bar"`
}
...

ex := map[string]any{"bar": true}
schema.Example = ex 

I think it would make a lot of sense to extend the examples or docs to contain an example for this. Generally, allowing to use structs here could also be beneficial imho.