package openapi3gen

import "github.com/getkin/kin-openapi/openapi3gen"

Package openapi3gen generates OpenAPIv3 JSON schemas from Go types.

Example

Code:play 

package main

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/getkin/kin-openapi/openapi3gen"
)

type (
	SomeStruct struct {
		Bool    bool                      `json:"bool"`
		Int     int                       `json:"int"`
		Int64   int64                     `json:"int64"`
		Float64 float64                   `json:"float64"`
		String  string                    `json:"string"`
		Bytes   []byte                    `json:"bytes"`
		JSON    json.RawMessage           `json:"json"`
		Time    time.Time                 `json:"time"`
		Slice   []SomeOtherType           `json:"slice"`
		Map     map[string]*SomeOtherType `json:"map"`

		Struct struct {
			X string `json:"x"`
		} `json:"struct"`

		EmptyStruct struct {
			Y string
		} `json:"structWithoutFields"`

		Ptr *SomeOtherType `json:"ptr"`
	}

	SomeOtherType string
)

func main() {
	schemaRef, err := openapi3gen.NewSchemaRefForValue(&SomeStruct{}, nil)
	if err != nil {
		panic(err)
	}

	data, err := json.MarshalIndent(schemaRef, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", data)
}

Output:

{
  "properties": {
    "bool": {
      "type": "boolean"
    },
    "bytes": {
      "format": "byte",
      "type": "string"
    },
    "float64": {
      "format": "double",
      "type": "number"
    },
    "int": {
      "type": "integer"
    },
    "int64": {
      "format": "int64",
      "type": "integer"
    },
    "json": {},
    "map": {
      "additionalProperties": {
        "type": "string"
      },
      "type": "object"
    },
    "ptr": {
      "type": "string"
    },
    "slice": {
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "string": {
      "type": "string"
    },
    "struct": {
      "properties": {
        "x": {
          "type": "string"
        }
      },
      "type": "object"
    },
    "structWithoutFields": {},
    "time": {
      "format": "date-time",
      "type": "string"
    }
  },
  "type": "object"
}

Index

Examples

Variables

var RefSchemaRef = openapi3.NewSchemaRef("Ref",
	openapi3.NewObjectSchema().WithProperty("$ref", openapi3.NewStringSchema().WithMinLength(1)))

Functions

func NewSchemaRefForValue

func NewSchemaRefForValue(value interface{}, schemas openapi3.Schemas, opts ...Option) (*openapi3.SchemaRef, error)

NewSchemaRefForValue is a shortcut for NewGenerator(...).NewSchemaRefForValue(...)

Example (Recursive)

Code:play 

package main

import (
	"encoding/json"
	"fmt"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/openapi3gen"
)

func main() {
	type RecursiveType struct {
		Field1     string           `json:"field1"`
		Field2     string           `json:"field2"`
		Field3     string           `json:"field3"`
		Components []*RecursiveType `json:"children,omitempty"`
	}

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(&RecursiveType{}, schemas)
	if err != nil {
		panic(err)
	}

	var data []byte
	if data, err = json.MarshalIndent(&schemas, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf("schemas: %s\n", data)
	if data, err = json.MarshalIndent(&schemaRef, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf("schemaRef: %s\n", data)
}

Output:

schemas: {
  "RecursiveType": {
    "properties": {
      "children": {
        "items": {
          "$ref": "#/components/schemas/RecursiveType"
        },
        "type": "array"
      },
      "field1": {
        "type": "string"
      },
      "field2": {
        "type": "string"
      },
      "field3": {
        "type": "string"
      }
    },
    "type": "object"
  }
}
schemaRef: {
  "properties": {
    "children": {
      "items": {
        "$ref": "#/components/schemas/RecursiveType"
      },
      "type": "array"
    },
    "field1": {
      "type": "string"
    },
    "field2": {
      "type": "string"
    },
    "field3": {
      "type": "string"
    }
  },
  "type": "object"
}

Types

type CycleError

type CycleError struct{}

CycleError indicates that a type graph has one or more possible cycles.

func (*CycleError) Error

func (err *CycleError) Error() string

type ExcludeSchemaSentinel

type ExcludeSchemaSentinel struct{}

ExcludeSchemaSentinel indicates that the schema for a specific field should not be included in the final output.

func (*ExcludeSchemaSentinel) Error

func (err *ExcludeSchemaSentinel) Error() string

type Generator

type Generator struct {
	Types map[reflect.Type]*openapi3.SchemaRef

	// SchemaRefs contains all references and their counts.
	// If count is 1, it's not ne
	// An OpenAPI identifier has been assigned to each.
	SchemaRefs map[*openapi3.SchemaRef]int
	// contains filtered or unexported fields
}

func NewGenerator

func NewGenerator(opts ...Option) *Generator

func (*Generator) GenerateSchemaRef

func (g *Generator) GenerateSchemaRef(t reflect.Type) (*openapi3.SchemaRef, error)
Example

Code:play 

package main

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/getkin/kin-openapi/openapi3gen"
)

func main() {
	type EmbeddedStruct struct {
		ID string
	}

	type ContainerStruct struct {
		Name string
		EmbeddedStruct
	}

	instance := &ContainerStruct{
		Name: "Container",
		EmbeddedStruct: EmbeddedStruct{
			ID: "Embedded",
		},
	}

	generator := openapi3gen.NewGenerator(openapi3gen.UseAllExportedFields())

	schemaRef, err := generator.GenerateSchemaRef(reflect.TypeOf(instance))
	if err != nil {
		panic(err)
	}

	var data []byte
	if data, err = json.MarshalIndent(schemaRef.Value.Properties["Name"].Value, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf(`schemaRef.Value.Properties["Name"].Value: %s`, data)
	fmt.Println()
	if data, err = json.MarshalIndent(schemaRef.Value.Properties["ID"].Value, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf(`schemaRef.Value.Properties["ID"].Value: %s`, data)
	fmt.Println()
}

Output:

schemaRef.Value.Properties["Name"].Value: {
  "type": "string"
}
schemaRef.Value.Properties["ID"].Value: {
  "type": "string"
}

func (*Generator) NewSchemaRefForValue

func (g *Generator) NewSchemaRefForValue(value interface{}, schemas openapi3.Schemas) (*openapi3.SchemaRef, error)

NewSchemaRefForValue uses reflection on the given value to produce a SchemaRef, and updates a supplied map with any dependent component schemas if they lead to cycles

type Option

type Option func(*generatorOpt)

Option allows tweaking SchemaRef generation

func SchemaCustomizer

func SchemaCustomizer(sc SchemaCustomizerFn) Option

SchemaCustomizer allows customization of the schema that is generated for a field, for example to support an additional tagging scheme

Example

Code:play 

package main

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/openapi3gen"
)

func main() {
	type NestedInnerBla struct {
		Enum1Field string `json:"enum1" myenumtag:"a,b"`
	}

	type InnerBla struct {
		UntaggedStringField string
		AnonStruct          struct {
			InnerFieldWithoutTag int
			InnerFieldWithTag    int `mymintag:"-1" mymaxtag:"50"`
			NestedInnerBla
		}
		Enum2Field string `json:"enum2" myenumtag:"c,d"`
	}

	type Bla struct {
		InnerBla
		EnumField3 string `json:"enum3" myenumtag:"e,f"`
	}

	customizer := openapi3gen.SchemaCustomizer(func(name string, ft reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
		if tag.Get("mymintag") != "" {
			minVal, err := strconv.ParseFloat(tag.Get("mymintag"), 64)
			if err != nil {
				return err
			}
			schema.Min = &minVal
		}
		if tag.Get("mymaxtag") != "" {
			maxVal, err := strconv.ParseFloat(tag.Get("mymaxtag"), 64)
			if err != nil {
				return err
			}
			schema.Max = &maxVal
		}
		if tag.Get("myenumtag") != "" {
			for _, s := range strings.Split(tag.Get("myenumtag"), ",") {
				schema.Enum = append(schema.Enum, s)
			}
		}
		return nil
	})

	schemaRef, err := openapi3gen.NewSchemaRefForValue(&Bla{}, nil, openapi3gen.UseAllExportedFields(), customizer)
	if err != nil {
		panic(err)
	}

	var data []byte
	if data, err = json.MarshalIndent(schemaRef, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf("schemaRef: %s\n", data)
}

Output:

schemaRef: {
  "properties": {
    "AnonStruct": {
      "properties": {
        "InnerFieldWithTag": {
          "maximum": 50,
          "minimum": -1,
          "type": "integer"
        },
        "InnerFieldWithoutTag": {
          "type": "integer"
        },
        "enum1": {
          "enum": [
            "a",
            "b"
          ],
          "type": "string"
        }
      },
      "type": "object"
    },
    "UntaggedStringField": {
      "type": "string"
    },
    "enum2": {
      "enum": [
        "c",
        "d"
      ],
      "type": "string"
    },
    "enum3": {
      "enum": [
        "e",
        "f"
      ],
      "type": "string"
    }
  },
  "type": "object"
}

func ThrowErrorOnCycle

func ThrowErrorOnCycle() Option

ThrowErrorOnCycle changes the default behavior of creating cycle refs to instead error if a cycle is detected.

Example

Code:play 

package main

import (
	"encoding/json"
	"fmt"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/openapi3gen"
)

func main() {
	type CyclicType0 struct {
		CyclicField *struct {
			CyclicField *CyclicType0 `json:"b"`
		} `json:"a"`
	}

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(&CyclicType0{}, schemas, openapi3gen.ThrowErrorOnCycle())
	if schemaRef != nil || err == nil {
		panic(`With option ThrowErrorOnCycle, an error is returned when a schema reference cycle is found`)
	}
	if _, ok := err.(*openapi3gen.CycleError); !ok {
		panic(`With option ThrowErrorOnCycle, an error of type CycleError is returned`)
	}
	if len(schemas) != 0 {
		panic(`No references should have been collected at this point`)
	}

	if schemaRef, err = openapi3gen.NewSchemaRefForValue(&CyclicType0{}, schemas); err != nil {
		panic(err)
	}

	var data []byte
	if data, err = json.MarshalIndent(schemaRef, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf("schemaRef: %s\n", data)
	if data, err = json.MarshalIndent(schemas, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf("schemas: %s\n", data)
}

Output:

schemaRef: {
  "properties": {
    "a": {
      "properties": {
        "b": {
          "$ref": "#/components/schemas/CyclicType0"
        }
      },
      "type": "object"
    }
  },
  "type": "object"
}
schemas: {
  "CyclicType0": {
    "properties": {
      "a": {
        "properties": {
          "b": {
            "$ref": "#/components/schemas/CyclicType0"
          }
        },
        "type": "object"
      }
    },
    "type": "object"
  }
}

func UseAllExportedFields

func UseAllExportedFields() Option

UseAllExportedFields changes the default behavior of only generating schemas for struct fields with a JSON tag.

Example

Code:play 

package main

import (
	"encoding/json"
	"fmt"

	"github.com/getkin/kin-openapi/openapi3gen"
)

func main() {
	type UnsignedIntStruct struct {
		UnsignedInt uint `json:"uint"`
	}

	schemaRef, err := openapi3gen.NewSchemaRefForValue(&UnsignedIntStruct{}, nil, openapi3gen.UseAllExportedFields())
	if err != nil {
		panic(err)
	}

	var data []byte
	if data, err = json.MarshalIndent(schemaRef, "", "  "); err != nil {
		panic(err)
	}
	fmt.Printf("schemaRef: %s\n", data)
}

Output:

schemaRef: {
  "properties": {
    "uint": {
      "minimum": 0,
      "type": "integer"
    }
  },
  "type": "object"
}

type SchemaCustomizerFn

type SchemaCustomizerFn func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error

SchemaCustomizerFn is a callback function, allowing the OpenAPI schema definition to be updated with additional properties during the generation process, based on the name of the field, the Go type, and the struct tags. name will be "_root" for the top level object, and tag will be "". A SchemaCustomizerFn can return an ExcludeSchemaSentinel error to indicate that the schema for this field should not be included in the final output

Source Files

openapi3gen.go

Version
v0.107.0
Published
Oct 27, 2022
Platform
linux/amd64
Imports
8 packages
Last checked
53 seconds ago

Tools for package owners.