openapi2jsonschema

package module
v0.0.0-...-609d621 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: MIT Imports: 8 Imported by: 0

README

openapi2jsonschema

A Go library that converts OpenAPI 3.x documents to JSON Schema Draft 2020-12.

Install

go get github.com/bdwyertech/go-openapi2jsonschema

Usage

Convert all schemas
package main

import (
	"fmt"
	"os"

	openapi2jsonschema "github.com/bdwyertech/go-openapi2jsonschema"
)

func main() {
	input, _ := os.ReadFile("k8s-openapi.json")

	// Convert all component schemas to JSON Schema
	schema, err := openapi2jsonschema.Convert(input)
	if err != nil {
		panic(err)
	}

	output, _ := json.MarshalIndent(schema, "", "  ")
	fmt.Println(string(output))
}
Convert a single schema
// Get a JSON Schema rooted at a specific type
schema, err := openapi2jsonschema.ConvertSchema(input, "io.k8s.api.core.v1.Pod")
Convert to JSON bytes directly
jsonBytes, err := openapi2jsonschema.ConvertToJSON(input)
Read from io.Reader
schema, err := openapi2jsonschema.ConvertReader(resp.Body)

Options

// Set $id on the root schema
schema, _ := openapi2jsonschema.Convert(input,
	openapi2jsonschema.WithSchemaID("https://kubernetes.io/schemas"),
)

// Preserve x-kubernetes-* extensions in output
schema, _ := openapi2jsonschema.Convert(input,
	openapi2jsonschema.WithPreserveKubernetesExtensions(),
)

// Strip all x-* extensions
schema, _ := openapi2jsonschema.Convert(input,
	openapi2jsonschema.WithStripExtensions(),
)

What it does

OpenAPI 3.x JSON Schema Draft 2020-12
#/components/schemas/X #/$defs/X
nullable: true type: ["string", "null"]
discriminator stripped
xml stripped
externalDocs stripped
example stripped
readOnly / writeOnly preserved
allOf / oneOf / anyOf / not preserved
additionalProperties (bool or schema) preserved
x-kubernetes-* configurable (stripped by default)

Output format

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$defs": {
    "io.k8s.api.core.v1.Pod": { ... },
    "io.k8s.api.core.v1.PodSpec": { ... }
  }
}

When using ConvertSchema() for a single type:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$ref": "#/$defs/io.k8s.api.core.v1.Pod",
  "$defs": { ... }
}

Dependencies

License

MIT

Documentation

Overview

Package openapi2jsonschema converts OpenAPI 3.x documents to JSON Schema Draft 2020-12.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertToJSON

func ConvertToJSON(input []byte, opts ...Option) ([]byte, error)

ConvertToJSON is a convenience function that converts an OpenAPI 3.x document to a JSON Schema and returns it as indented JSON bytes.

Types

type BoolOrSchema

type BoolOrSchema struct {
	Bool   *bool
	Schema *JSONSchema
}

BoolOrSchema represents a value that can be either a boolean or a JSON Schema. In Draft 2020-12, additionalProperties can be true, false, or a schema object.

func BoolSchema

func BoolSchema(b bool) *BoolOrSchema

BoolSchema creates a BoolOrSchema with a boolean value.

func SchemaValue

func SchemaValue(s *JSONSchema) *BoolOrSchema

SchemaValue creates a BoolOrSchema with a schema value.

func (*BoolOrSchema) MarshalJSON

func (bs *BoolOrSchema) MarshalJSON() ([]byte, error)

MarshalJSON outputs either a boolean or a schema object.

func (*BoolOrSchema) UnmarshalJSON

func (bs *BoolOrSchema) UnmarshalJSON(data []byte) error

UnmarshalJSON handles both boolean and schema forms.

type JSONSchema

type JSONSchema struct {
	Schema  string `json:"$schema,omitempty"`
	ID      string `json:"$id,omitempty"`
	Ref     string `json:"$ref,omitempty"`
	Comment string `json:"$comment,omitempty"`

	// Core
	Type        *SchemaType            `json:"type,omitempty"`
	Title       string                 `json:"title,omitempty"`
	Description string                 `json:"description,omitempty"`
	Default     any                    `json:"default,omitempty"`
	Enum        []any                  `json:"enum,omitempty"`
	Const       any                    `json:"const,omitempty"`
	Examples    []any                  `json:"examples,omitempty"`
	Defs        map[string]*JSONSchema `json:"$defs,omitempty"`

	// Numeric
	MultipleOf       *float64 `json:"multipleOf,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty"`
	ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
	Minimum          *float64 `json:"minimum,omitempty"`
	ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`

	// String
	MaxLength *int64 `json:"maxLength,omitempty"`
	MinLength *int64 `json:"minLength,omitempty"`
	Pattern   string `json:"pattern,omitempty"`
	Format    string `json:"format,omitempty"`

	// Array
	Items       *JSONSchema   `json:"items,omitempty"`
	PrefixItems []*JSONSchema `json:"prefixItems,omitempty"`
	MaxItems    *int64        `json:"maxItems,omitempty"`
	MinItems    *int64        `json:"minItems,omitempty"`
	UniqueItems *bool         `json:"uniqueItems,omitempty"`
	Contains    *JSONSchema   `json:"contains,omitempty"`

	// Object
	MaxProperties        *int64                 `json:"maxProperties,omitempty"`
	MinProperties        *int64                 `json:"minProperties,omitempty"`
	Required             []string               `json:"required,omitempty"`
	Properties           map[string]*JSONSchema `json:"properties,omitempty"`
	PatternProperties    map[string]*JSONSchema `json:"patternProperties,omitempty"`
	AdditionalProperties *BoolOrSchema          `json:"additionalProperties,omitempty"`
	PropertyNames        *JSONSchema            `json:"propertyNames,omitempty"`

	// Composition
	AllOf []*JSONSchema `json:"allOf,omitempty"`
	AnyOf []*JSONSchema `json:"anyOf,omitempty"`
	OneOf []*JSONSchema `json:"oneOf,omitempty"`
	Not   *JSONSchema   `json:"not,omitempty"`

	// Conditional
	If   *JSONSchema `json:"if,omitempty"`
	Then *JSONSchema `json:"then,omitempty"`
	Else *JSONSchema `json:"else,omitempty"`

	// Metadata
	ReadOnly  *bool `json:"readOnly,omitempty"`
	WriteOnly *bool `json:"writeOnly,omitempty"`

	// Extensions (x-kubernetes-* etc.) stored as extra keys
	Extensions map[string]any `json:"-"`
}

JSONSchema represents a JSON Schema Draft 2020-12 document or sub-schema. Fields are pointers or omitempty to produce clean, minimal output.

func Convert

func Convert(input []byte, opts ...Option) (*JSONSchema, error)

Convert parses an OpenAPI 3.x document from bytes and returns a JSON Schema Draft 2020-12 document containing all component schemas as $defs.

func ConvertReader

func ConvertReader(r io.Reader, opts ...Option) (*JSONSchema, error)

ConvertReader reads an OpenAPI 3.x document from an io.Reader and returns a JSON Schema Draft 2020-12 document.

func ConvertSchema

func ConvertSchema(input []byte, schemaName string, opts ...Option) (*JSONSchema, error)

ConvertSchema parses an OpenAPI 3.x document and returns a JSON Schema for a single named schema. The root schema will have a $ref pointing to the named schema in $defs, and only referenced schemas are included.

func ConvertSchemaByKindSuffix

func ConvertSchemaByKindSuffix(input []byte, kind string, opts ...Option) (*JSONSchema, error)

ConvertSchemaByKindSuffix parses an OpenAPI 3.x document and returns a JSON Schema for the schema whose key ends with ".{kind}" (e.g. ".VerticalPodAutoscaler"). This is useful for Kubernetes schemas where the full key is like "io.k8s.autoscaling.v1.VerticalPodAutoscaler" but callers only know the Kind.

func (*JSONSchema) MarshalJSON

func (s *JSONSchema) MarshalJSON() ([]byte, error)

MarshalJSON implements custom marshaling to include extension fields alongside the standard schema fields.

type Option

type Option func(*config)

Option configures the conversion behavior.

func WithPreserveKubernetesExtensions

func WithPreserveKubernetesExtensions() Option

WithPreserveKubernetesExtensions keeps x-kubernetes-* extension fields in the output JSON Schema. By default they are stripped.

func WithSchemaID

func WithSchemaID(id string) Option

WithSchemaID sets the $id field on the root JSON Schema output.

func WithStripExtensions

func WithStripExtensions() Option

WithStripExtensions removes all x-* extension fields from the output. This takes precedence over WithPreserveKubernetesExtensions.

type SchemaType

type SchemaType struct {
	Types []string
}

SchemaType handles JSON Schema's type field which can be a string or array of strings.

func NullableType

func NullableType(t string) *SchemaType

NullableType creates a SchemaType pointer that includes "null" alongside the given type.

func SingleType

func SingleType(t string) *SchemaType

SingleType creates a SchemaType pointer with a single type string.

func (*SchemaType) IsEmpty

func (t *SchemaType) IsEmpty() bool

IsEmpty returns true if no types are set.

func (*SchemaType) MarshalJSON

func (t *SchemaType) MarshalJSON() ([]byte, error)

MarshalJSON outputs a single string if there's one type, or an array if multiple.

func (*SchemaType) UnmarshalJSON

func (t *SchemaType) UnmarshalJSON(data []byte) error

UnmarshalJSON handles both string and array forms.

Jump to

Keyboard shortcuts

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