getkin / kin-openapi

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

Best method for including example of defined input? #296

Open badloop opened 3 years ago

badloop commented 3 years ago

I am attempting to allow a user-defined struct to define what the input schema for an API would be. I've found the NewSchemaRefForValue function that does successfully generate the properties block for a given struct, but there doesn't appear to be a way to provide example input using that function. Is there a method for achieving this currently?

fenollp commented 3 years ago

Does this help? https://pkg.go.dev/github.com/getkin/kin-openapi/openapi3gen

badloop commented 3 years ago

@fenollp thats the code I'm using... openapi3gen.NewSchemaRefForValue seems to do a fine job of generating the Schema object, but there is no way of generating that Schema object with included examples. The examples would need to be added to the object manually after the Schema was created.

So the following works for making the schema object:

type MyStruct struct {
    MyField string `json:"myfield"`
}
s, _, _ := openapi3gen.NewSchemaRefForValue(&MyStruct{})

But I would then need to manipulate that object to add examples for each field. Obviously for this example that is trivial, but for a more complex struct it would quickly become very cumbersome. Ideally I would be able to do something like the following:

type MyStruct struct {
    MyField string `json:"myfield" oapi-example:"this string should look like this"`
}
s, _, _ := openapi3gen.NewSchemaRefForValue(&MyStruct{})

And it would populate the example automatically. I've dug into the code a bit and the fix to allow something like that would be to add fields to the jsoninfo struct for processing. Not sure if this is a direction that the project wants to go though.

Thoughts?

fenollp commented 3 years ago

What is stopping you from setting s.Example? https://github.com/getkin/kin-openapi/blob/66309f4b3e518c98adc86fa99c2c38e268b43745/openapi3/schema.go#L109