oas

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2023 License: Unlicense Imports: 10 Imported by: 0

README

Overview

"oas" is short for "OpenAPI Spec". Go package that generates JSON-schemas and OpenAPI docs from Go types and structures, at runtime.

Non-features:

  • No CLI.
  • No code parsing.
  • No code generation.
  • No magic comments.
  • No slowness.
  • No dependencies.
  • Nothing added to your HTTP stack.

Features:

  • Generates JSON schema definitions from Go types and structures.
  • Provides struct types describing OpenAPI 3.1.
  • Uses reflection to make OAS schemas from your types and structures.
    • No more maintaining type definitions by hand in separate files.
    • The source of truth is your Go types. Not some external YAML.
    • Examines actual encoding behavior of your types, at runtime, to determine formats and nullability.
    • Supports references and cyclic types.
  • Uses Go structs to describe what can't be reflected (routes, descriptions, etc).
    • Structured, statically-typed format.
    • Not an ad-hoc data format in breakage-prone comments.
    • Not some external YAML.
  • The docs are Go structures. You can do anything with them:
    • Inspect and modify in Go.
    • Encode as JSON or YAML.
    • Write to disk or stdout at build time.
    • Serve to clients at runtime.
    • Visualize using an external tool.
  • Tiny and dependency-free.

See limitations below.

API docs: https://pkg.go.dev/github.com/mitranim/oas

Why

  • No external CLI. Just a library.
    • Automatically downloaded by Go.
    • Automatically versioned via go.mod.
    • No manual CLI installation.
    • No manual CLI versioning.
  • No Go code generation.
    • No make generate when pulling or switching branches.
    • No waiting 1 minute for that stupidly slow generator.
    • No manual remapping from crappy generated types to the types you actually want to use.
    • No crappy 3rd party "middleware" in your HTTP stack.
  • No forced generation of OAS files. It's entirely optional.
    • No manual reruns of a generate command.
    • No bloating your commits and Git diffs with generated JSON/YAML.
    • Can generate and serve OAS purely at runtime.
  • No figuring out how to deal with built artifacts.
    • If you want built artifacts, it's an option. Your Go app is a CLI tool. Add a command to encode its OAS as JSON, and run that at build time.

Usage

This example focuses on the OAS docs, registering docs for routes, with schemas from Go types. Routing and server setup is elided.

import (
  "encoding/json"
  "net/http"

  o "github.com/mitranim/oas"
)

var doc = o.Doc{
  Openapi: o.Ver,
  Info:    &o.Info{Title: `API documentation for my server`},
}

type PageInput struct {
  Limit  uint64 `json:"limit"`
  Offset uint64 `json:"offset"`
}

type PersonPage struct {
  PageHead
  Vals []Person `json:"vals"`
}

type PageHead struct {
  Keys []string `json:"keys"`
  More bool     `json:"more"`
}

type Person struct {
  Id   string `json:"id"`
  Name string `json:"name"`
}

var _ = doc.Route(`/api/persons`, http.MethodGet, o.Op{
  ReqBody: doc.JsonBodyOpt(PageInput{}),
  Resps:   doc.RespsOkJson(PersonPage{}),
  Desc:    `Serves a single page from a person feed, paginated.`,
})

func servePersonFeed(rew http.ResponseWriter, req *http.Request) {
  // Mock implementation for example's sake.
  try(json.NewEncoder(rew).Encode(PersonPage{}))
}

var _ = doc.Route(`/openapi.json`, http.MethodGet, o.Op{
  Resps: doc.RespsOkJson(nil),
  Desc: `
Serves the OpenAPI documentation for this server in JSON format.
The docs' docs are elided from the docs to avoid bloat.
`,
})

func serveDocs(rew http.ResponseWriter, _ *http.Request) {
  try(json.NewEncoder(rew).Encode(&doc))
}

func try(err error) {
  if err != nil {
    panic(err)
  }
}

Limitations

The following features are currently missing, but may be added on demand:

  • Describing generic/parametrized types.
    • Current plan: wait for Go generics, which are expected in 1.18 on Feb 2022.
  • Router integration.
    • Integration with github.com/mitranim/rout is planned.

This package doesn't provide a UI. You're expected to feed the resulting JSON into one of many externally-available tools for Swagger UI / OpenAPI UI. Many tools can consume specs from a URL, such as your server's endpoint for serving the spec.

License

https://unlicense.org

Misc

I'm receptive to suggestions. If this library almost satisfies you but needs changes, open an issue or chat me up. Contacts: https://mitranim.com/#contacts

Documentation

Overview

References:

https://oai.github.io/Documentation/

https://spec.openapis.org/oas/v3.1.0

https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00

https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00

Index

Constants

View Source
const (
	// OpenAPI version supported by this package.
	Ver = `3.1.0`

	TypeNull = `null`
	TypeInt  = `integer`
	TypeNum  = `number`
	TypeStr  = `string`
	TypeBool = `boolean`
	TypeObj  = `object`
	TypeArr  = `array`

	/**
	References:

		https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-7.3

		https://swagger.io/docs/specification/data-models/data-types/

	The following are the formats that this package automatically detects.
	*/
	FormatInt32    = `int32`
	FormatInt64    = `int64`
	FormatFloat32  = `float`
	FormatFloat64  = `double`
	FormatDate     = `date`
	FormatTime     = `time`
	FormatDateTime = `date-time`
	FormatDuration = `duration`
	FormatUuid     = `uuid`

	// Well-known formats that this package doesn't automatically detect.
	FormatByte     = `byte`
	FormatBin      = `binary`
	FormatPassword = `password`
	FormatEmail    = `email`

	// Reference: https://spec.openapis.org/oas/v3.1.0#parameter-locations
	InPath   = `path`
	InQuery  = `query`
	InHeader = `header`
	InCookie = `cookie`

	ConTypeJson = `application/json`
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Anys

type Anys map[string]any

Represents maps of "any type" in some OAS definitions.

type Body

type Body struct {
	Ref  string     `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum  string     `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc string     `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Cont MediaTypes `json:"content,omitempty"  yaml:"content,omitempty"  toml:"content,omitempty"`
	Requ bool       `json:"required,omitempty" yaml:"required,omitempty" toml:"required,omitempty"`
}

Short for "request body": https://spec.openapis.org/oas/v3.1.0#request-body-object

func (Body) Opt

func (self Body) Opt() *Body

Value method that returns a pointer. Sometimes useful as a shortcut.

type Callback

type Callback map[string]string

https://spec.openapis.org/oas/v3.1.0#callback-object. May also be `{"$ref": "..."}`.

type Comps

type Comps struct {
	Ref        string     `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum        string     `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc       string     `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Schemas    Schemas    `json:"schemas,omitempty"         yaml:"schemas,omitempty"         toml:"schemas,omitempty"`
	Resps      Resps      `json:"responses,omitempty"       yaml:"responses,omitempty"       toml:"responses,omitempty"`
	Params     Params     `json:"parameters,omitempty"      yaml:"parameters,omitempty"      toml:"parameters,omitempty"`
	Examples   Examples   `json:"examples,omitempty"        yaml:"examples,omitempty"        toml:"examples,omitempty"`
	Reqs       Bodies     `json:"requestBodies,omitempty"   yaml:"requestBodies,omitempty"   toml:"requestBodies,omitempty"`
	Heads      Heads      `json:"headers,omitempty"         yaml:"headers,omitempty"         toml:"headers,omitempty"`
	SecSchemes SecSchemes `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty" toml:"securitySchemes,omitempty"`
	Links      Links      `json:"links,omitempty"           yaml:"links,omitempty"           toml:"links,omitempty"`
	Callbacks  Callbacks  `json:"callbacks,omitempty"       yaml:"callbacks,omitempty"       toml:"callbacks,omitempty"`
	Paths      Paths      `json:"pathItems,omitempty"       yaml:"pathItems,omitempty"       toml:"pathItems,omitempty"`
}

Short for "components": https://spec.openapis.org/oas/v3.1.0#components-object

type Contact

type Contact struct {
	Ref   string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum   string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc  string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Name  string `json:"name,omitempty"  yaml:"name,omitempty"  toml:"name,omitempty"`
	Url   string `json:"url,omitempty"   yaml:"url,omitempty"   toml:"url,omitempty"`
	Email string `json:"email,omitempty" yaml:"email,omitempty" toml:"email,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#contact-object

type Discr

type Discr struct {
	Ref  string            `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum  string            `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc string            `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Prop string            `json:"propertyName,omitempty" yaml:"propertyName,omitempty" toml:"propertyName,omitempty"`
	Map  map[string]string `json:"mapping,omitempty"      yaml:"mapping,omitempty"      toml:"mapping,omitempty"`
}

Short for "discriminator": https://spec.openapis.org/oas/v3.1.0#discriminator-object

type Doc

type Doc struct {
	Ref        string   `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum        string   `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc       string   `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Openapi    string   `json:"openapi,omitempty"           yaml:"openapi,omitempty"           toml:"openapi,omitempty"`
	Info       *Info    `json:"info,omitempty"              yaml:"info,omitempty"              toml:"info,omitempty"`
	JsonSchema string   `json:"jsonSchemaDialect,omitempty" yaml:"jsonSchemaDialect,omitempty" toml:"jsonSchemaDialect,omitempty"`
	Servers    []Server `json:"servers,omitempty"           yaml:"servers,omitempty"           toml:"servers,omitempty"`
	Paths      Paths    `json:"paths,omitempty"             yaml:"paths,omitempty"             toml:"paths,omitempty"`
	Webhooks   Paths    `json:"webhooks,omitempty"          yaml:"webhooks,omitempty"          toml:"webhooks,omitempty"`
	Comps      Comps    `json:"components,omitempty"        yaml:"components,omitempty"        toml:"components,omitempty"`
	Security   []SecReq `json:"security,omitempty"          yaml:"security,omitempty"          toml:"security,omitempty"`
	Tags       []Tag    `json:"tags,omitempty"              yaml:"tags,omitempty"              toml:"tags,omitempty"`
	ExtDoc     *ExtDoc  `json:"externalDocs,omitempty"      yaml:"externalDocs,omitempty"      toml:"externalDocs,omitempty"`
}

Top-level OpenAPI document. Reference:

https://spec.openapis.org/oas/v3.1.0#openapi-object

func (*Doc) DerefSchema

func (self *Doc) DerefSchema(sch Schema) (Schema, bool)

Dereferences the given schema, returning a non-reference. The bool is true if the target schema was found, false otherwise. May panic if the schema unexpectedly has double indirection.

func (*Doc) GotCompSchema

func (self *Doc) GotCompSchema(name string) (Schema, bool)

Looks up a schema by the given name among the doc's components. The name must be the exact schema title, not a reference path. May panic if the schema unexpectedly has double indirection.

func (*Doc) GotSchema

func (self *Doc) GotSchema(refPath string) (Schema, bool)

Looks up the schema by a full reference path. Currently supports only component references starting with `#/components/schemas/`.

func (*Doc) JsonBody

func (self *Doc) JsonBody(typ interface{}) Body

Shortcut. Returns `oas.Body` describing a JSON response with the schema of the given type, after registering its schema in the document. The input is used only as a type carrier; its actual value is ignored.

func (*Doc) JsonBodyOpt

func (self *Doc) JsonBodyOpt(typ interface{}) *Body

Same as `.JsonBody(typ).Opt()` but slightly clearer.

func (*Doc) RespsOkJson

func (self *Doc) RespsOkJson(typ interface{}) Resps

Shortcut. Returns `oas.Resps` with 200 JSON for the given type, after registering its schema in the document. The input is used only as a type carrier; its actual value is ignored.

func (*Doc) Route

func (self *Doc) Route(path, meth string, op Op) *Doc

Shortcut for registering a route via `oas.Doc.Paths.Route`.

func (*Doc) Sch

func (self *Doc) Sch(typ interface{}) Schema

Shortcut for returning `.TypeSchema` from the input's type. The input value is used only as a type carrier.

func (*Doc) SchemaMedia

func (self *Doc) SchemaMedia(typ interface{}) MediaType

Shortcut. Returns `oas.MediaType` with the schema of the given type, after registering its schema in the document. The input is used only as a type carrier; its actual value is ignored.

func (*Doc) TypeSchema

func (self *Doc) TypeSchema(typ r.Type) (sch Schema)

Returns an OAS schema for the given Go type. May register various associated types in `.Comps.Schemas`, mutating the document. The returned schema may be a reference.

type Encoding

type Encoding struct {
	Ref      string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum      string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc     string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	ConType  string `json:"contentType,omitempty"   yaml:"contentType,omitempty"   toml:"contentType,omitempty"`
	Head     Heads  `json:"headers,omitempty"       yaml:"headers,omitempty"       toml:"headers,omitempty"`
	Style    string `json:"style,omitempty"         yaml:"style,omitempty"         toml:"style,omitempty"`
	Explode  bool   `json:"explode,omitempty"       yaml:"explode,omitempty"       toml:"explode,omitempty"`
	Reserved bool   `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty" toml:"allowReserved,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#encoding-object

type Example

type Example struct {
	Ref   string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum   string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc  string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Val   string `json:"value,omitempty"         yaml:"value,omitempty"         toml:"value,omitempty"`
	ExVal string `json:"externalValue,omitempty" yaml:"externalValue,omitempty" toml:"externalValue,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#example-object

type ExtDoc

type ExtDoc struct {
	Ref  string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum  string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Url  string `json:"url,omitempty"         yaml:"url,omitempty"         toml:"url,omitempty"`
}

Short for "external documentation": https://spec.openapis.org/oas/v3.1.0#external-documentation-object

type Flow

type Flow struct {
	Ref        string            `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum        string            `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc       string            `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	AuthUrl    string            `json:"authorizationUrl,omitempty" yaml:"authorizationUrl,omitempty"  toml:"authorizationUrl,omitempty"`
	TokenUrl   string            `json:"tokenUrl,omitempty"         yaml:"tokenUrl,omitempty"          toml:"tokenUrl,omitempty"`
	RefreshUrl string            `json:"refreshUrl,omitempty"       yaml:"refreshUrl,omitempty"        toml:"refreshUrl,omitempty"`
	Scopes     map[string]string `json:"scopes,omitempty"           yaml:"scopes,omitempty"            toml:"scopes,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#oauth-flow-object

type Flows

type Flows struct {
	Ref        string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum        string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc       string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Implicit   Flow   `json:"implicit,omitempty"          yaml:"implicit,omitempty"          toml:"implicit,omitempty"`
	Password   Flow   `json:"password,omitempty"          yaml:"password,omitempty"          toml:"password,omitempty"`
	ClientCred Flow   `json:"clientCredentials,omitempty" yaml:"clientCredentials,omitempty" toml:"clientCredentials,omitempty"`
	AuthCode   Flow   `json:"authorizationCode,omitempty" yaml:"authorizationCode,omitempty" toml:"authorizationCode,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#oauth-flows-object

type Head struct {
	Ref      string     `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum      string     `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc     string     `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Requ     bool       `json:"required,omitempty"        yaml:"required,omitempty"        toml:"required,omitempty"`
	Depr     bool       `json:"deprecated,omitempty"      yaml:"deprecated,omitempty"      toml:"deprecated,omitempty"`
	Empty    bool       `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty" toml:"allowEmptyValue,omitempty"`
	Style    string     `json:"style,omitempty"           yaml:"style,omitempty"           toml:"style,omitempty"`
	Explode  bool       `json:"explode,omitempty"         yaml:"explode,omitempty"         toml:"explode,omitempty"`
	Reserved bool       `json:"allowReserved,omitempty"   yaml:"allowReserved,omitempty"   toml:"allowReserved,omitempty"`
	Schema   *Schema    `json:"schema,omitempty"          yaml:"schema,omitempty"          toml:"schema,omitempty"`
	Example  any        `json:"example,omitempty"         yaml:"example,omitempty"         toml:"example,omitempty"`
	Examples Examples   `json:"examples,omitempty"        yaml:"examples,omitempty"        toml:"examples,omitempty"`
	Cont     MediaTypes `json:"content,omitempty"         yaml:"content,omitempty"         toml:"content,omitempty"`
}

Short for "header": https://spec.openapis.org/oas/v3.1.0#header-object

type Info

type Info struct {
	Ref     string   `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum     string   `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc    string   `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Title   string   `json:"title,omitempty"          yaml:"title,omitempty"          toml:"title,omitempty"`
	Terms   string   `json:"termsOfService,omitempty" yaml:"termsOfService,omitempty" toml:"termsOfService,omitempty"`
	Contact *Contact `json:"contact,omitempty"        yaml:"contact,omitempty"        toml:"contact,omitempty"`
	License *License `json:"license,omitempty"        yaml:"license,omitempty"        toml:"license,omitempty"`
	Ver     string   `json:"version,omitempty"        yaml:"version,omitempty"        toml:"version,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#info-object

type License

type License struct {
	Ref   string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum   string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc  string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Name  string `json:"name,omitempty"       yaml:"name,omitempty"       toml:"name,omitempty"`
	Ident string `json:"identifier,omitempty" yaml:"identifier,omitempty" toml:"identifier,omitempty"`
	Url   string `json:"url,omitempty"        yaml:"url,omitempty"        toml:"url,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#license-object

type Link struct {
	Ref     string  `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum     string  `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc    string  `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	OpRef   string  `json:"operationRef,omitempty" yaml:"operationRef,omitempty" toml:"operationRef,omitempty"`
	OpId    string  `json:"operationId,omitempty"  yaml:"operationId,omitempty"  toml:"operationId,omitempty"`
	Params  Anys    `json:"parameters,omitempty"   yaml:"parameters,omitempty"   toml:"parameters,omitempty"`
	ReqBody any     `json:"requestBody,omitempty"  yaml:"requestBody,omitempty"  toml:"requestBody,omitempty"`
	Server  *Server `json:"server,omitempty"       yaml:"server,omitempty"       toml:"server,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#link-object

type MediaType

type MediaType struct {
	Ref      string    `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum      string    `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc     string    `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Schema   Schema    `json:"schema,omitempty"   yaml:"schema,omitempty"   toml:"schema,omitempty"`
	Example  any       `json:"example,omitempty"  yaml:"example,omitempty"  toml:"example,omitempty"`
	Examples Examples  `json:"examples,omitempty" yaml:"examples,omitempty" toml:"examples,omitempty"`
	Encoding Encodings `json:"encoding,omitempty" yaml:"encoding,omitempty" toml:"encoding,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#media-type-object

type Op

type Op struct {
	Ref       string    `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum       string    `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc      string    `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Tags      []Tag     `json:"tags,omitempty"         yaml:"tags,omitempty"         toml:"tags,omitempty"`
	ExtDoc    *ExtDoc   `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty" toml:"externalDocs,omitempty"`
	OpId      string    `json:"operationId,omitempty"  yaml:"operationId,omitempty"  toml:"operationId,omitempty"`
	Params    []Param   `json:"parameters,omitempty"   yaml:"parameters,omitempty"   toml:"parameters,omitempty"`
	ReqBody   *Body     `json:"requestBody,omitempty"  yaml:"requestBody,omitempty"  toml:"requestBody,omitempty"`
	Resps     Resps     `json:"responses,omitempty"    yaml:"responses,omitempty"    toml:"responses,omitempty"`
	Callbacks Callbacks `json:"callbacks,omitempty"    yaml:"callbacks,omitempty"    toml:"callbacks,omitempty"`
	Depr      bool      `json:"deprecated,omitempty"   yaml:"deprecated,omitempty"   toml:"deprecated,omitempty"`
	Sec       []SecReq  `json:"security,omitempty"     yaml:"security,omitempty"     toml:"security,omitempty"`
	Servers   []Server  `json:"servers,omitempty"      yaml:"servers,omitempty"      toml:"servers,omitempty"`
}

Short for "operation": https://spec.openapis.org/oas/v3.1.0#operation-object

type Param

type Param struct {
	Head
	Name string `json:"name,omitempty" yaml:"name,omitempty" toml:"name,omitempty"`
	In   string `json:"in,omitempty"   yaml:"in,omitempty"   toml:"in,omitempty"`
}

Short for "parameter": https://spec.openapis.org/oas/v3.1.0#parameter-object

type Path

type Path struct {
	Ref     string   `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum     string   `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc    string   `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Get     *Op      `json:"get,omitempty"         yaml:"get,omitempty"         toml:"get,omitempty"`
	Put     *Op      `json:"put,omitempty"         yaml:"put,omitempty"         toml:"put,omitempty"`
	Post    *Op      `json:"post,omitempty"        yaml:"post,omitempty"        toml:"post,omitempty"`
	Delete  *Op      `json:"delete,omitempty"      yaml:"delete,omitempty"      toml:"delete,omitempty"`
	Options *Op      `json:"options,omitempty"     yaml:"options,omitempty"     toml:"options,omitempty"`
	Head    *Op      `json:"head,omitempty"        yaml:"head,omitempty"        toml:"head,omitempty"`
	Patch   *Op      `json:"patch,omitempty"       yaml:"patch,omitempty"       toml:"patch,omitempty"`
	Trace   *Op      `json:"trace,omitempty"       yaml:"trace,omitempty"       toml:"trace,omitempty"`
	Servers []Server `json:"servers,omitempty"     yaml:"servers,omitempty"     toml:"servers,omitempty"`
	Params  []Param  `json:"parameters,omitempty"  yaml:"parameters,omitempty"  toml:"parameters,omitempty"`
}

Called "path item" in the spec: https://spec.openapis.org/oas/v3.1.0#path-item-object

func (*Path) Method

func (self *Path) Method(meth string, op Op) *Path

Sets the "op" at the given method. The method must be well-known, otherwise this will panic.

type Paths

type Paths map[string]Path

https://spec.openapis.org/oas/v3.1.0#paths-object

func (*Paths) Init

func (self *Paths) Init() Paths

Inits the receiving variable or property to non-nil, returning the resulting mutable map. Handy for chaining.

func (Paths) Route

func (self Paths) Route(path, meth string, op Op) Paths

Shortcut for registering an "op" at the given path and method, via `(*oas.Path).Method`.

type Ref

type Ref struct {
	Ref  string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum  string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
}

Reference object. References:

https://spec.openapis.org/oas/v3.1.0#reference-object

https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.3.1

Most of our types have a `Ref string` field, and technically they should embed this type to avoid unnecessary duplication. However, we copy the fields instead of embedding the type to ensure better compatibility with 3rd party encoders, some of which don't seem to support embedded structs, particularly for YAML.

type Resp

type Resp struct {
	Ref   string     `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum   string     `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc  string     `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Head  Heads      `json:"headers,omitempty"     yaml:"headers,omitempty"     toml:"headers,omitempty"`
	Cont  MediaTypes `json:"content,omitempty"     yaml:"content,omitempty"     toml:"content,omitempty"`
	Links Links      `json:"links,omitempty"       yaml:"links,omitempty"       toml:"links,omitempty"`
}

Short for "response": https://spec.openapis.org/oas/v3.1.0#response-object

type Schema

type Schema struct {
	// Ref `json:",omitempty" yaml:",omitempty" toml:",omitempty"`
	// Ref
	Ref  string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum  string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`

	Discr   *Discr  `json:"discriminator,omitempty" yaml:"discriminator,omitempty" toml:"discriminator,omitempty"`
	Xml     *Xml    `json:"xml,omitempty"           yaml:"xml,omitempty"           toml:"xml,omitempty"`
	ExtDoc  *ExtDoc `json:"externalDocs,omitempty"  yaml:"externalDocs,omitempty"  toml:"externalDocs,omitempty"`
	Example any     `json:"example,omitempty"       yaml:"example,omitempty"       toml:"example,omitempty"` // Also see `.Examples`.

	// Subschemas.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-10.2.1
	AllOf []Schema `json:"allOf,omitempty" yaml:"allOf,omitempty" toml:"allOf,omitempty"`
	AnyOf []Schema `json:"anyOf,omitempty" yaml:"anyOf,omitempty" toml:"anyOf,omitempty"`
	OneOf []Schema `json:"oneOf,omitempty" yaml:"oneOf,omitempty" toml:"oneOf,omitempty"`
	Not   *Schema  `json:"not,omitempty"   yaml:"not,omitempty"   toml:"not,omitempty"`

	// Conditional subschemas.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-10.2.2
	If         *Schema `json:"if,omitempty"               yaml:"if,omitempty"               toml:"if,omitempty"`
	Then       *Schema `json:"then,omitempty"             yaml:"then,omitempty"             toml:"then,omitempty"`
	Else       *Schema `json:"else,omitempty"             yaml:"else,omitempty"             toml:"else,omitempty"`
	DepSchemas Schemas `json:"dependentSchemas,omitempty" yaml:"dependentSchemas,omitempty" toml:"dependentSchemas,omitempty"`

	// Array child schemas.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-10.3.1
	PrefixItems []Schema `json:"prefixItems,omitempty" yaml:"prefixItems,omitempty" toml:"prefixItems,omitempty"`
	Items       *Schema  `json:"items,omitempty"       yaml:"items,omitempty"       toml:"items,omitempty"`
	Contains    *Schema  `json:"contains,omitempty"    yaml:"contains,omitempty"    toml:"contains,omitempty"`

	// Object subschemas.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-10.3.2
	Props     Schemas `json:"properties,omitempty"           yaml:"properties,omitempty"           toml:"properties,omitempty"`
	PatProps  Schemas `json:"patternProperties,omitempty"    yaml:"patternProperties,omitempty"    toml:"patternProperties,omitempty"`
	AddProps  *Schema `json:"additionalProperties,omitempty" yaml:"additionalProperties,omitempty" toml:"additionalProperties,omitempty"`
	PropNames *Schema `json:"propertyNames,omitempty"        yaml:"propertyNames,omitempty"        toml:"propertyNames,omitempty"`

	// Unevaluated locations.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-11
	UnevalItems *Schema `json:"unevaluatedItems,omitempty"      yaml:"unevaluatedItems,omitempty"      toml:"unevaluatedItems,omitempty"`
	UnevalProps *Schema `json:"unevaluatedProperties,omitempty" yaml:"unevaluatedProperties,omitempty" toml:"unevaluatedProperties,omitempty"`

	// Validation for any instance.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-6.1
	Type  []string `json:"type,omitempty"  yaml:"type,omitempty"  toml:"type,omitempty"`
	Enum  []string `json:"enum,omitempty"  yaml:"enum,omitempty"  toml:"enum,omitempty"`
	Const any      `json:"const,omitempty" yaml:"const,omitempty"                       toml:"const,omitempty"`

	// Validation for numeric instances.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-6.2
	MulOf   uint64 `json:"multipleOf,omitempty"       yaml:"multipleOf,omitempty"       toml:"multipleOf,omitempty"` // 0 represents "missing".
	Max     *int64 `json:"maximum,omitempty"          yaml:"maximum,omitempty"          toml:"maximum,omitempty"`
	ExlcMax *int64 `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty" toml:"exclusiveMaximum,omitempty"`
	Min     *int64 `json:"minimum,omitempty"          yaml:"minimum,omitempty"          toml:"minimum,omitempty"`
	ExclMin *int64 `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty" toml:"exclusiveMinimum,omitempty"`

	// Validation for strings.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-6.3
	MaxLen  uint64 `json:"maxLength,omitempty" yaml:"maxLength,omitempty" toml:"maxLength,omitempty"` // 0 represents "missing".
	MinLen  uint64 `json:"minLength,omitempty" yaml:"minLength,omitempty" toml:"minLength,omitempty"`
	Pattern string `json:"pattern,omitempty"   yaml:"pattern,omitempty"   toml:"pattern,omitempty"`

	// Validation for arrays.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-6.4
	MaxItems  uint64 `json:"maxItems,omitempty"    yaml:"maxItems,omitempty"    toml:"maxItems,omitempty"`
	MinItems  uint64 `json:"minItems,omitempty"    yaml:"minItems,omitempty"    toml:"minItems,omitempty"`
	UniqItems bool   `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty" toml:"uniqueItems,omitempty"`
	MaxCont   uint64 `json:"maxContains,omitempty" yaml:"maxContains,omitempty" toml:"maxContains,omitempty"`
	MinCont   uint64 `json:"minContains,omitempty" yaml:"minContains,omitempty" toml:"minContains,omitempty"`

	// Validation for objects.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-6.5
	MaxProps uint64              `json:"maxProperties,omitempty"     yaml:"maxProperties,omitempty"     toml:"maxProperties,omitempty"`
	MinProps uint64              `json:"minProperties,omitempty"     yaml:"minProperties,omitempty"     toml:"minProperties,omitempty"`
	Requ     bool                `json:"required,omitempty"          yaml:"required,omitempty"          toml:"required,omitempty"`
	DepRequ  map[string][]string `json:"dependentRequired,omitempty" yaml:"dependentRequired,omitempty" toml:"dependentRequired,omitempty"`

	// Format.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-7
	Format string `json:"format,omitempty" yaml:"format,omitempty" toml:"format,omitempty"`

	// Validation of string-encoded data.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-8
	ContEnc    string `json:"contentEncoding,omitempty"  yaml:"contentEncoding,omitempty"  toml:"contentEncoding,omitempty"`
	ContMedia  string `json:"contentMediaType,omitempty" yaml:"contentMediaType,omitempty" toml:"contentMediaType,omitempty"`
	ContSchema string `json:"contentSchema,omitempty"    yaml:"contentSchema,omitempty"    toml:"contentSchema,omitempty"`

	// Metadata annotations.
	// https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-9
	Title string `json:"title,omitempty"       yaml:"title,omitempty"       toml:"title,omitempty"`
	// Desc     string   `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Default  any      `json:"default,omitempty"     yaml:"default,omitempty"     toml:"default,omitempty"`
	Depr     bool     `json:"deprecated,omitempty"  yaml:"deprecated,omitempty"  toml:"deprecated,omitempty"`
	Ronly    bool     `json:"readOnly,omitempty"    yaml:"readOnly,omitempty"    toml:"readOnly,omitempty"`
	Wonly    bool     `json:"writeOnly,omitempty"   yaml:"writeOnly,omitempty"   toml:"writeOnly,omitempty"`
	Examples Examples `json:"examples,omitempty"    yaml:"examples,omitempty"    toml:"examples,omitempty"`
}

References:

https://spec.openapis.org/oas/v3.1.0#schema-object

https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00

https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00

The properties are listed in the order of their definition in the respective specifications, on a best-effort basis.

func NullSchema

func NullSchema(name string, inner Schema) Schema

Shortcut for making a schema that wraps another and uses `.OneOf` with `oas.TypeNull` to indicate nullability. Mostly for internal use; you should never have to annotate nullability manually, as this package detects it automatically.

func RefSchema

func RefSchema(name string) (out Schema)

func (Schema) IsNullable

func (self Schema) IsNullable() bool

True if either `.Type`, `.OneOf`, or `.AnyOf` indicates nullability. Note that while `true` indicates nullability, `false` does NOT indicate non-nullability, as the type may reference another, which in turn may be inherently nullable.

func (*Schema) Nullable

func (self *Schema) Nullable()

Mostly for internal use. Mutates the receiver to indicate nullability by adding `oas.TypeNull` to the type. For indicating nullability by wrapping, see `NullSchema`.

func (Schema) Opt

func (self Schema) Opt() *Schema

Value method that returns a pointer. Sometimes useful as a shortcut.

func (*Schema) TypeAdd

func (self *Schema) TypeAdd(vals ...string) *Schema

Adds `vals` to `.Type`, deduplicating them, like a set.

func (Schema) TypeHas

func (self Schema) TypeHas(exp string) bool

True if the given primitive type is among `.Type`.

func (Schema) TypeIs

func (self Schema) TypeIs(exp ...string) bool

True if `.Type` exactly matches the given inputs.

func (*Schema) TypeReplace

func (self *Schema) TypeReplace(vals ...string) *Schema

Replaces `.Type` with the given vals.

func (Schema) ValidTitle

func (self Schema) ValidTitle() string

Returns `.Title` after validating that it's non-empty.

type Schemas

type Schemas map[string]Schema

See the doc on the `oas.Schema` type.

func (*Schemas) Init

func (self *Schemas) Init() Schemas

Inits the receiving variable or property to non-nil, returning the resulting mutable map. Handy for chaining.

type SecReq

type SecReq map[string][]string

Short for "secutity requirement".

type SecScheme

type SecScheme struct {
	Ref        string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum        string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc       string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Type       string `json:"type,omitempty"             yaml:"type,omitempty"             toml:"type,omitempty"`
	Name       string `json:"name,omitempty"             yaml:"name,omitempty"             toml:"name,omitempty"`
	In         string `json:"in,omitempty"               yaml:"in,omitempty"               toml:"in,omitempty"`
	Scheme     string `json:"scheme,omitempty"           yaml:"scheme,omitempty"           toml:"scheme,omitempty"`
	BearFormat string `json:"bearerFormat,omitempty"     yaml:"bearerFormat,omitempty"     toml:"bearerFormat,omitempty"`
	Flows      *Flows `json:"flows,omitempty"            yaml:"flows,omitempty"            toml:"flows,omitempty"`
	OidUrl     string `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty" toml:"openIdConnectUrl,omitempty"`
}

Short for "security scheme". https://spec.openapis.org/oas/v3.1.0#security-scheme-object

type Server

type Server struct {
	Ref  string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum  string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Url  string `json:"url,omitempty"         yaml:"url,omitempty"         toml:"url,omitempty"`
	Vars Vars   `json:"variables,omitempty"   yaml:"variables,omitempty"   toml:"variables,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#server-object

type Tag

type Tag struct {
	Ref    string  `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum    string  `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc   string  `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Name   string  `json:"name,omitempty"         yaml:"name,omitempty"         toml:"name,omitempty"`
	ExtDoc *ExtDoc `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty" toml:"externalDocs,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#tag-object

type Var

type Var struct {
	Ref     string   `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum     string   `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc    string   `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Enum    []string `json:"enum,omitempty"        yaml:"enum,omitempty"        toml:"enum,omitempty"`
	Default string   `json:"default,omitempty"     yaml:"default,omitempty"     toml:"default,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#server-variable-object

type Xml

type Xml struct {
	Ref    string `json:"$ref,omitempty"        yaml:"$ref,omitempty"        toml:"$ref,omitempty"`
	Sum    string `json:"sum,omitempty"         yaml:"sum,omitempty"         toml:"sum,omitempty"`
	Desc   string `json:"description,omitempty" yaml:"description,omitempty" toml:"description,omitempty"`
	Name   string `json:"name,omitempty"      yaml:"name,omitempty"      toml:"name,omitempty"`
	Nspace string `json:"namespace,omitempty" yaml:"namespace,omitempty" toml:"namespace,omitempty"`
	Prefix string `json:"prefix,omitempty"    yaml:"prefix,omitempty"    toml:"prefix,omitempty"`
	Attr   bool   `json:"attribute,omitempty" yaml:"attribute,omitempty" toml:"attribute,omitempty"`
	Wrap   bool   `json:"wrapped,omitempty"   yaml:"wrapped,omitempty"   toml:"wrapped,omitempty"`
}

https://spec.openapis.org/oas/v3.1.0#xml-object

Jump to

Keyboard shortcuts

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