kin-openapi icon indicating copy to clipboard operation
kin-openapi copied to clipboard

Best method for including example of defined input?

Open badloop opened this issue 5 years ago • 3 comments

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?

badloop avatar Feb 03 '21 14:02 badloop

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

fenollp avatar Feb 04 '21 06:02 fenollp

@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?

badloop avatar Feb 04 '21 13:02 badloop

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

fenollp avatar Feb 15 '21 06:02 fenollp