openapi3gen

package
v0.124.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 6, 2024 License: MIT Imports: 12 Imported by: 31

Documentation

Overview

Package openapi3gen generates OpenAPIv3 JSON schemas from Go types.

Example
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

Constants

This section is empty.

Variables

View Source
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)
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"
}
Example (WithExportingSchemas)
package main

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

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

func main() {
	type Child struct {
		Age string `json:"age"`
	}
	type AnotherStruct struct {
		Field1 string `json:"field1"`
		Field2 string `json:"field2"`
		Field3 string `json:"field3"`
	}
	type RecursiveType struct {
		Field1        string        `json:"field1"`
		Field2        string        `json:"field2"`
		Field3        string        `json:"field3"`
		AnotherStruct AnotherStruct `json:"children,omitempty"`
		Child         subpkg.Child  `json:"child"`
		Child2        Child         `json:"child2"`
	}

	// sample of a type name generator
	typeNameGenerator := func(t reflect.Type) string {
		packages := strings.Split(t.PkgPath(), "/")
		return packages[len(packages)-1] + "_" + t.Name()
	}

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(
		&RecursiveType{},
		schemas,
		openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
			ExportComponentSchemas: true, ExportTopLevelSchema: false,
		}),
		openapi3gen.CreateTypeNameGenerator(typeNameGenerator),
		openapi3gen.UseAllExportedFields(),
	)
	if err != nil {
		panic(err)
	}

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

schemas: {
  "openapi3gen_test_AnotherStruct": {
    "properties": {
      "field1": {
        "type": "string"
      },
      "field2": {
        "type": "string"
      },
      "field3": {
        "type": "string"
      }
    },
    "type": "object"
  },
  "openapi3gen_test_Child": {
    "properties": {
      "age": {
        "type": "string"
      }
    },
    "type": "object"
  },
  "subpkg_Child": {
    "properties": {
      "name": {
        "type": "string"
      }
    },
    "type": "object"
  }
}
schemaRef: {
  "properties": {
    "child": {
      "$ref": "#/components/schemas/subpkg_Child"
    },
    "child2": {
      "$ref": "#/components/schemas/openapi3gen_test_Child"
    },
    "children": {
      "$ref": "#/components/schemas/openapi3gen_test_AnotherStruct"
    },
    "field1": {
      "type": "string"
    },
    "field2": {
      "type": "string"
    },
    "field3": {
      "type": "string"
    }
  },
  "type": "object"
}
Example (WithExportingSchemasIgnoreTopLevelParent)
package main

import (
	"encoding/json"
	"fmt"

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

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

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(&RecursiveType{}, schemas, openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
		ExportComponentSchemas: true, ExportTopLevelSchema: false,
	}))
	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: {
  "AnotherStruct": {
    "properties": {
      "field1": {
        "type": "string"
      },
      "field2": {
        "type": "string"
      },
      "field3": {
        "type": "string"
      }
    },
    "type": "object"
  }
}
schemaRef: {
  "properties": {
    "children": {
      "$ref": "#/components/schemas/AnotherStruct"
    },
    "field1": {
      "type": "string"
    },
    "field2": {
      "type": "string"
    },
    "field3": {
      "type": "string"
    }
  },
  "type": "object"
}
Example (WithExportingSchemasWithGeneric)
package main

import (
	"encoding/json"
	"fmt"

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

func main() {
	type Child struct {
		Age string `json:"age"`
	}
	type GenericStruct[T any] struct {
		GenericField T     `json:"genericField"`
		Child        Child `json:"child"`
	}
	type AnotherStruct struct {
		Field1 string `json:"field1"`
		Field2 string `json:"field2"`
		Field3 string `json:"field3"`
	}
	type RecursiveType struct {
		Field1        string                `json:"field1"`
		Field2        string                `json:"field2"`
		Field3        string                `json:"field3"`
		AnotherStruct AnotherStruct         `json:"children,omitempty"`
		Child         Child                 `json:"child"`
		GenericStruct GenericStruct[string] `json:"genericChild"`
	}

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(
		&RecursiveType{},
		schemas,
		openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
			ExportComponentSchemas: true, ExportTopLevelSchema: true, ExportGenerics: false,
		}),
		openapi3gen.UseAllExportedFields(),
	)
	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: {
  "AnotherStruct": {
    "properties": {
      "field1": {
        "type": "string"
      },
      "field2": {
        "type": "string"
      },
      "field3": {
        "type": "string"
      }
    },
    "type": "object"
  },
  "Child": {
    "properties": {
      "age": {
        "type": "string"
      }
    },
    "type": "object"
  },
  "RecursiveType": {
    "properties": {
      "child": {
        "$ref": "#/components/schemas/Child"
      },
      "children": {
        "$ref": "#/components/schemas/AnotherStruct"
      },
      "field1": {
        "type": "string"
      },
      "field2": {
        "type": "string"
      },
      "field3": {
        "type": "string"
      },
      "genericChild": {
        "properties": {
          "child": {
            "$ref": "#/components/schemas/Child"
          },
          "genericField": {
            "type": "string"
          }
        },
        "type": "object"
      }
    },
    "type": "object"
  }
}
schemaRef: {
  "$ref": "#/components/schemas/RecursiveType"
}
Example (WithExportingSchemasWithMap)
package main

import (
	"encoding/json"
	"fmt"

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

func main() {
	type Child struct {
		Age string `json:"age"`
	}
	type MyType struct {
		Field1 string                 `json:"field1"`
		Field2 string                 `json:"field2"`
		Map1   map[string]interface{} `json:"anymap"`
		Map2   map[string]Child       `json:"anymapChild"`
	}

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(
		&MyType{},
		schemas,
		openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
			ExportComponentSchemas: true, ExportTopLevelSchema: false, ExportGenerics: true,
		}),
		openapi3gen.UseAllExportedFields(),
	)
	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: {
  "Child": {
    "properties": {
      "age": {
        "type": "string"
      }
    },
    "type": "object"
  }
}
schemaRef: {
  "properties": {
    "anymap": {
      "additionalProperties": {},
      "type": "object"
    },
    "anymapChild": {
      "additionalProperties": {
        "$ref": "#/components/schemas/Child"
      },
      "type": "object"
    },
    "field1": {
      "type": "string"
    },
    "field2": {
      "type": "string"
    }
  },
  "type": "object"
}
Example (WithSubPackages)

Make sure that custom schema name generator is employed and results produced with it are properly used

package main

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

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

func main() {
	type Parent struct {
		Field1 string       `json:"field1"`
		Child  subpkg.Child `json:"child"`
	}

	// these schema names should be returned by name generator
	parentSchemaName := "PARENT_TYPE"
	childSchemaName := "CHILD_TYPE"

	// sample of a type name generator
	typeNameGenerator := func(t reflect.Type) string {
		switch t {
		case reflect.TypeOf(Parent{}):
			return parentSchemaName
		case reflect.TypeOf(subpkg.Child{}):
			return childSchemaName
		}
		return t.Name()
	}

	schemas := make(openapi3.Schemas)
	schemaRef, err := openapi3gen.NewSchemaRefForValue(
		&Parent{},
		schemas,
		openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
			ExportComponentSchemas: true, ExportTopLevelSchema: true,
		}),
		openapi3gen.CreateTypeNameGenerator(typeNameGenerator),
		openapi3gen.UseAllExportedFields(),
	)
	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: {
  "CHILD_TYPE": {
    "properties": {
      "name": {
        "type": "string"
      }
    },
    "type": "object"
  },
  "PARENT_TYPE": {
    "properties": {
      "child": {
        "$ref": "#/components/schemas/CHILD_TYPE"
      },
      "field1": {
        "type": "string"
      }
    },
    "type": "object"
  }
}
schemaRef: {
  "$ref": "#/components/schemas/PARENT_TYPE"
}

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 added in v0.95.0

type ExcludeSchemaSentinel struct{}

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

func (*ExcludeSchemaSentinel) Error added in v0.95.0

func (err *ExcludeSchemaSentinel) Error() string

type ExportComponentSchemasOptions added in v0.124.0

type ExportComponentSchemasOptions struct {
	ExportComponentSchemas bool
	ExportTopLevelSchema   bool
	ExportGenerics         bool
}

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
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 added in v0.84.0

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 added in v0.48.0

type Option func(*generatorOpt)

Option allows tweaking SchemaRef generation

func CreateComponentSchemas added in v0.124.0

func CreateComponentSchemas(exso ExportComponentSchemasOptions) Option

CreateComponents changes the default behavior to add all schemas as components Reduces duplicate schemas in routes

func CreateTypeNameGenerator added in v0.124.0

func CreateTypeNameGenerator(tngnrt TypeNameGenerator) Option

func SchemaCustomizer added in v0.75.0

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
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 added in v0.73.0

func ThrowErrorOnCycle() Option

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

Example
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 added in v0.48.0

func UseAllExportedFields() Option

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

Example
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 added in v0.75.0

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

type SetSchemar added in v0.124.0

type SetSchemar interface {
	SetSchema(*openapi3.Schema)
}

SetSchemar allows client to set their own schema definition according to their specification. Useful when some custom datatype is needed and/or some custom logic is needed on how the schema values would be generated

Example
package main

import (
	"encoding/json"
	"fmt"

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

type ID [16]byte

// T implements SetSchemar, allowing it to set an OpenAPI schema.
type T struct {
	ID ID `json:"id"`
}

func (_ *ID) SetSchema(schema *openapi3.Schema) {
	schema.Type = &openapi3.Types{"string"}
	schema.Format = "uuid"
}

func main() {
	schemas := make(openapi3.Schemas)
	instance := &T{
		ID: ID{},
	}

	// Generate the schema for the instance
	schemaRef, err := openapi3gen.NewSchemaRefForValue(instance, schemas)
	if err != nil {
		panic(err)
	}
	data, err := json.MarshalIndent(schemaRef, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("schemaRef: %s\n", data)
}
Output:

schemaRef: {
  "properties": {
    "id": {
      "format": "uuid",
      "type": "string"
    }
  },
  "type": "object"
}

type TypeNameGenerator added in v0.124.0

type TypeNameGenerator func(t reflect.Type) string

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL