openapi

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 28 Imported by: 32 modules, 29 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package openapi provides functionality for mapping CUE to and from OpenAPI.

Generate and Gen translate a CUE value into the schema components of an OpenAPI v3.0 document. GenerateV2 translates a CUE value shaped like a whole OpenAPI document (v3.0 or v3.1) into that document; the rest of this package documentation concerns GenerateV2 only.

Schema positions and the "#" convention

When generating a whole document with GenerateV2, the input is ordinary CUE data mirroring the OpenAPI document structure (info, paths, servers, security and so on), and it is emitted verbatim. The exception is the positions where the OpenAPI specification expects a Schema Object: there, the generator looks for a "#" definition holding a CUE schema and converts that schema into a JSON Schema.

A reference to an existing top-level schema is therefore written by placing that schema behind a "#" field rather than at the schema position directly:

#Person: {name: string, age?: int}

paths: "/people": get: responses: "200": content: "application/json": schema: #: #Person

An inline schema is written the same way:

paths: "/people": get: responses: "200": content: "application/json": schema: #: {name: string, age?: int}

Writing `schema: #Person` directly (without the intervening "#") does not have the same meaning. The "#" marker is required, rather than interpreting whatever is found at a schema position as a schema, for several reasons:

  • It keeps the distinction between data and schema explicit. Everything outside a "#" is data emitted verbatim; only the contents of a "#" are interpreted as a CUE schema to be converted. Schema positions are not limited to fields named "schema", so a name-based rule would not suffice.
  • It keeps the input a well-formed CUE encoding of an OpenAPI document. Because "#" fields are definitions, the document still conforms to the OpenAPI specification and can, for example, be exported as JSON with cue export (the schema parts are simply omitted). Placing a bare CUE schema at a Schema Object position would instead constrain the eventual data there, so the document as a whole would no longer be a plain OpenAPI document matching the specification, which requires a JSON Schema in that position.

If a schema position contains no "#" definition, whatever value is found there is used verbatim as the JSON Schema. A "#" definition and sibling data fields cannot be combined at the same schema position; doing so is an error.

See https://spec.openapis.org/oas/ for the OpenAPI specification.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Extract added in v0.1.0

func Extract(data cue.InstanceOrValue, c *Config) (*ast.File, error)

Extract converts OpenAPI definitions to an equivalent CUE representation.

It currently only converts entries in #/components/schema and extracts some meta data.

The result can be converted to a cue.Value via cue.Context.BuildFile.

func ExtractV2 added in v0.18.0

func ExtractV2(data cue.Value, cfg *ExtractConfig) (*ast.File, error)

ExtractV2 converts a whole OpenAPI document to an equivalent CUE representation. It is the inverse of GenerateV2: the result is shaped so that passing it back through GenerateV2 reproduces an equivalent document.

Each entry under components.schemas becomes a top-level # definition (or, when its name is not a valid identifier, a quoted field of the anonymous # definition). At each position where an OpenAPI Schema Object is expected, the schema is extracted into CUE and placed under a # field; a Reference Object ({$ref: "#/components/schemas/Foo"}) becomes a reference to the corresponding definition. All other document content is preserved verbatim.

The result can be converted to a cue.Value via cue.Context.BuildFile.

Note: The form of the extracted representation may, and probably will, change from release to release.

THIS IS EXPERIMENTAL. API MIGHT CHANGE.

func Gen deprecated

func Gen(inst cue.InstanceOrValue, c *Config) ([]byte, error)

Gen generates the set OpenAPI schema for all top-level types of the given instance.

Deprecated: use Generate.

func Generate added in v0.1.0

func Generate(inst cue.InstanceOrValue, c *Config) (*ast.File, error)

Generate generates the set of OpenAPI schema for all top-level types of the given instance.

Note: only a limited number of top-level types are supported so far.

func GenerateV2 added in v0.18.0

func GenerateV2(v cue.Value, cfg *GenerateConfig) (ast.Expr, error)

GenerateV2 generates an OpenAPI document from the given value.

The value should conform to an OpenAPI document structure, as documented at https://spec.openapis.org/oas/, except that in positions where a schema is expected the generation code looks for a # definition and generates the JSON Schema from that. If there is no # definition, it uses any JSON Schema value it finds there verbatim.

Schemas referenced from more than one position are emitted once, under components.schemas, and referenced with a $ref.

THIS IS EXPERIMENTAL. API MIGHT CHANGE.

Types

type Config

type Config struct {
	// PkgName defines to package name for a generated CUE package.
	PkgName string

	// Info specifies the info section of the OpenAPI document. To be a valid
	// OpenAPI document, it must include at least the title and version fields.
	// Info may be a *ast.StructLit or any type that marshals to JSON.
	Info interface{}

	// NameFunc allows users to specify an alternative representation
	// for references. It is called with the value passed to the top level
	// method or function and the path to the entity being generated.
	// If it returns an empty string the generator will  expand the type
	// in place and, if applicable, not generate a schema for that entity.
	//
	// Note: this only returns the final element of the /-separated
	// reference.
	NameFunc func(val cue.Value, path cue.Path) string

	// DescriptionFunc allows rewriting a description associated with a certain
	// field. A typical implementation compiles the description from the
	// comments obtains from the Doc method. No description field is added if
	// the empty string is returned.
	DescriptionFunc func(v cue.Value) string

	// Deprecated: SelfContained has no effect; all non-expanded external
	// references are always included in the generated document.
	SelfContained bool

	// OpenAPI version to use. Supported as of v3.0.0.
	Version string

	// FieldFilter defines a regular expression of all fields to omit from the
	// output. It is only allowed to filter fields that add additional
	// constraints. Fields that indicate basic types cannot be removed. It is
	// an error for such fields to be excluded by this filter.
	// Fields are qualified by their Object type. For instance, the
	// minimum field of the schema object is qualified as Schema/minimum.
	FieldFilter string

	// ExpandReferences replaces references with actual objects when generating
	// OpenAPI Schema. It is an error for an CUE value to refer to itself
	// if this option is used.
	ExpandReferences bool

	// StrictFeatures reports an error for features that are known
	// to be unsupported.
	StrictFeatures bool

	// StrictKeywords reports an error when unknown keywords
	// are encountered. For OpenAPI 3.0, this is implicitly always
	// true, as that specification explicitly prohibits unknown keywords
	// other than "x-" prefixed keywords.
	StrictKeywords bool
}

A Config defines options for converting CUE to and from OpenAPI.

type ExtractConfig added in v0.18.0

type ExtractConfig struct {
	// PkgName, if non-empty, adds a package clause to the extracted file.
	PkgName string

	// Version is the OpenAPI version of the document. When [VersionUnknown]
	// (the default), it is auto-detected from the document's "openapi" field.
	Version Version

	// StrictFeatures reports an error for JSON Schema features that are known
	// to be unsupported when extracting schemas.
	StrictFeatures bool

	// StrictKeywords reports an error when unknown JSON Schema keywords are
	// encountered when extracting schemas. For OpenAPI 3.0 this is implicitly
	// always true, as that specification prohibits unknown keywords other than
	// "x-" prefixed ones.
	StrictKeywords bool
}

ExtractConfig defines the configuration for ExtractV2.

type GenerateConfig added in v0.18.0

type GenerateConfig struct {
	// NamesFunc determines how to name the shared schemas generated within
	// components.schemas. It is passed all the distinct references made by the
	// schemas in the document and, when AllSchemas is set, a reference to each
	// top-level schema; it must set a distinct [jsonschema.CUERef.Name] for
	// each. If nil, a default naming scheme is used.
	NamesFunc func(refs []*jsonschema.CUERef)

	// DescriptionFunc returns the description for the given field. A typical
	// implementation compiles the description from the comments obtained from
	// the Doc method. No description field is added if the empty string is
	// returned. If this is nil, descriptions are derived from doc comments.
	DescriptionFunc func(v cue.Value) string

	// AllSchemas causes [GenerateV2] to generate an entry in components.schemas
	// for every top-level schema (definition) found in the value. When this is
	// false, schemas are only generated when referred to from within a #
	// field in a schema position in the OpenAPI document.
	AllSchemas bool

	// Version is the OpenAPI version to use. When [VersionUnknown] (the
	// default), it is auto-detected from the document's "openapi" field.
	Version Version
}

GenerateConfig defines the configuration for GenerateV2.

type Generator added in v0.0.4

type Generator = Config

type Version added in v0.18.0

type Version int

Version defines the version of an OpenAPI document.

const (
	VersionUnknown Version = iota
	Version3_0
	Version3_1
	VersionKubernetesCRD
)

Jump to

Keyboard shortcuts

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