Search code examples
goswaggeropenapijsonschema

Golang struct to Json schema


Hi I need to infer a json schema (github.com/go-openapi/spec.Schema) from a struct :

type Testcase struct {
    Id           string    `json:"id,omitempty"`            // id of this test case
    Name         string    `json:"name,omitempty"`          // name of this test case
    CreationDate time.Time `json:"creation_date,omitempty"` // timestamp when the scenario was first created
    UpdateDate   time.Time `json:"update_date,omitempty"`   // last update timestamp
    Steps        []Step    `json:"steps,omitempty"`         // list of steps  type:"[]StepCcs"
}

I can't find a simple way to do so. I guess that this is a prerequisite for many REST frameworks out there that generate open api spec from the code.

Can someone point me out to a package that contains such helper : ie

func toSchema(obj interface{}) (spec.Schema, error)

Solution

  • https://github.com/invopop/jsonschema

    is what you are looking for.

    type TestUser struct {
      ID            int                    `json:"id"`
      Name          string                 `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"`
      Friends       []int                  `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"`
      Tags          map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"`
      BirthDate     time.Time              `json:"birth_date,omitempty" jsonschema:"oneof_required=date"`
      YearOfBirth   string                 `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"`
      Metadata      interface{}            `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"`
      FavColor      string                 `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"`
    }
    

    Results in following JSON Schema:

    jsonschema.Reflect(&TestUser{})