openapi

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 15 Imported by: 0

README

OpenAPI generation

github.com/libtnb/validator/contrib/openapi generates OpenAPI 3.1 documents from Go request and response types. validate rules supply constraints; documentation tags and typed options supply the API's descriptions and examples. The module has no dependency on a web framework or application.

type CreateProduct struct {
	Name string `json:"name" validate:"required && max:100" openapi:"description=Product name,example=Notebook"`
	SKU  string `json:"sku" validate:"required" openapi:"description=Stock keeping unit,example=NOTE-001"`
}

type Product struct {
	ID   int64  `json:"id" openapi:"description=Product ID,example=42,readOnly"`
	Name string `json:"name" openapi:"description=Product name,example=Notebook"`
}

g := openapi.MustNew("Catalog API", "1.0.0",
	openapi.WithServer("https://api.example.com", "Production"),
	openapi.WithSecurityScheme("apiKey", openapi.APIKeyScheme("X-API-Key", openapi.HeaderLocation)),
	openapi.WithDefaultSecurity(openapi.SecurityRequirement{"apiKey"}),
)
err := g.Add[CreateProduct](http.MethodPost, "/products",
	openapi.WithOperationID("createProduct"),
	openapi.WithSummary("Create product"),
	openapi.WithDescription("Create a product in the catalog."),
	openapi.WithTags("Products"),
	openapi.WithRequestExample(CreateProduct{Name: "Notebook", SKU: "NOTE-001"}),
	openapi.WithResponse[Product](http.StatusCreated,
		openapi.ResponseDescription("Product created"),
		openapi.ResponseExample(Product{ID: 42, Name: "Notebook"}),
	),
)
// Handle err before rendering.
spec, err := g.JSON()

New returns configuration errors; MustNew panics on them. Add is transactional: a failed operation does not reserve an operation ID, allocate component names, or change existing paths. JSON sorts map keys for reproducible output. Document returns a deep copy that can be inspected or changed safely. A generator is not safe for concurrent use.

Field documentation

The generator reads only the openapi documentation tag on JSON properties and inferred uri / query parameters, including embedded structs, nested objects and array elements. Other libraries' tags such as default:"5s" are ignored. Properties inside openapi are comma-separated:

Property Meaning
description Field or parameter description; may contain CommonMark.
example A schema example, also attached to inferred parameters.
default A documented default; it does not assign a value at runtime.
deprecated Boolean flag; use it only when the field is deprecated.
readOnly Boolean flag indicating a response-only property.
writeOnly Boolean flag indicating a request-only property.
Name string `json:"name" openapi:"description=Product name,example=Notebook"`
OldID string `json:"oldId" openapi:"description='Compatibility identifier, use id instead',deprecated"`
Tags []string `json:"tags" openapi:"description=Labels,example=[\"new\",\"sale\"]"`
Enabled bool `json:"enabled" openapi:"example=false,default=false"`

Quote a value containing commas with single or double quotes. Quoted values support escaped quotes, backslash, newline, carriage return, and tab; Go struct tag escaping is applied first. JSON arrays and objects can be written directly without quoting the entire value. deprecated, readOnly, and writeOnly without = mean true; an explicit boolean value is also accepted. Unknown or duplicate properties are errors.

For a string schema, example=P-1 is string text and default='' is an empty string. For other types the value must be JSON of the effective schema type, including WithSchema overrides. Malformed JSON, primitive type mismatches, invalid boolean flags, and simultaneous readOnly / writeOnly produce contextual type-definition errors, just as malformed validate tags do. They are not ErrInvalidOption. This is not full JSON Schema validation of example constraints.

Documentation tags do not change runtime validation. Field descriptions belong to the particular property or parameter, so two fields referencing the same component can have different descriptions.

Operation and request options

  • WithOperationID(id) sets an explicit, nonblank ID, unique within the document.
  • WithSummary, WithDescription, WithTags, and Deprecated() describe the operation.
  • WithRequestDescription, RequestRequired(), RequestOptional(), and WithRequestExample describe the generated JSON body. They return an error for an operation without a body.
  • WithParameter(Parameter{...}) adds a path, query, header, or cookie parameter. If the same (in, name) was inferred, the explicit parameter replaces it completely, including its schema and required flag. Duplicate explicit parameters are rejected; header names are compared without case. A path parameter must be required and have a matching {name} placeholder.
openapi.WithParameter(openapi.Parameter{
	Name: "X-Request-Time", In: "header", Required: true,
	Description: "Request timestamp in Unix seconds",
	Schema: &openapi.Schema{Type: "integer"},
	Example: jsontext.Value("1700000000"),
})

Authorization is described through security schemes; Accept and Content-Type belong to media types. They cannot be added as header parameters. The generator continues to infer JSON request bodies for POST, PUT, and PATCH; adding metadata does not introduce a body for GET or DELETE.

Authentication

Construct schemes with APIKeyScheme(name, location) or HTTPScheme(scheme, bearerFormat), then register them with WithSecurityScheme. API key locations are HeaderLocation, QueryLocation, and CookieLocation. API-specific signing instructions belong in the scheme's Description field. The package does not implement signing or authentication.

scheme := openapi.HTTPScheme("bearer", "JWT")
scheme.Description = "Send the access token issued by the identity service."
openapi.WithSecurityScheme("bearer", scheme)

WithDefaultSecurity sets document-wide requirements. WithSecurity overrides them for one operation:

// Both credentials required (AND).
openapi.WithSecurity(openapi.SecurityRequirement{"apiKey", "bearer"})

// Either credential accepted (OR).
openapi.WithSecurity(
	openapi.SecurityRequirement{"apiKey"},
	openapi.SecurityRequirement{"bearer"},
)

// Public operation: emit security: [], overriding document defaults.
openapi.WithoutSecurity()

Omitting WithSecurity inherits the document setting. WithSecurity and WithDefaultSecurity require a first requirement argument. Empty requirements, duplicate scheme names within a requirement, and undefined scheme references are errors. An empty computed list cannot silently become a public declaration; that requires WithoutSecurity() explicitly. These scope-free requirements are serialized as standard OpenAPI objects with empty scope arrays. OAuth scopes are not exposed by this API. Default requirements may appear before their scheme definitions in New's option list.

Responses and JSON values

WithResponse[T] and WithDefaultResponse[T] accept ResponseDescription, ResponseExample, and ResponseHeader options. NoBody means no response content, not a JSON null body, and cannot have a response example.

openapi.WithResponse[any](http.StatusOK, openapi.ResponseExample(nil))

openapi.WithResponse[Problem](http.StatusTooManyRequests,
	openapi.ResponseHeader("Retry-After", openapi.Header{
		Description: "Seconds before retrying",
		Schema: &openapi.Schema{Type: "integer"},
		Example: jsontext.Value("1"),
	}),
)

Request and response example options serialize and snapshot their arguments. nil, false, 0, "", [], and {} remain distinct values. In the document model, examples, defaults and constants use jsontext.Value: a nil slice omits the member, while jsontext.Value("null") emits an explicit JSON null. Response headers use case-insensitive names; Content-Type comes from response content.

Custom wire types and schema transforms

Use WithSchema[T] when a type's JSON representation differs from what reflection can infer, such as a decimal that implements custom marshaling:

openapi.WithSchema[Money](&openapi.Schema{Type: "number"})

Use WithSchemaTransform[T] for named Go types to supplement an inferred schema without duplicating its fields. Built-in types such as string and anonymous types are rejected; WithSchema remains available for scalar wire formats. Schema supports AllOf, AnyOf, OneOf, and Not, alongside the existing constraints and the new JSON-valued metadata.

openapi.WithSchemaTransform[Contact](func(schema *openapi.Schema) error {
	schema.AnyOf = []*openapi.Schema{
		{Required: []string{"email"}},
		{Required: []string{"phone"}},
	}
	return nil
})

Transforms run when a type schema is inferred, before per-use field rules and metadata are attached. A struct's child properties already have their own rules and documentation. Ordinary named struct components are inferred once; top-level request bodies are inferred per operation. Inline named types and custom marshalers are transformed on every occurrence, so a transform on a named scalar affects every use of that named type, not built-in values with the same underlying type. For a top-level request the schema contains only body fields; path and query parameters remain separate. A whole-type WithSchema override has precedence over a transform. Transforms return errors when an assumed field or contract is missing, and a failed transform rolls back the entire Add. Transforms describe constraints; they do not enforce them in the application.

Pointer layers are ignored when registering either option. Overrides and transform results are copied, including numeric bounds and composition branches. Generic component names use OpenAPI's permitted characters, including types instantiated with any; name collisions still receive stable numeric suffixes.

Tests

From this directory:

go test ./...
go test -race ./...
go vet ./...

To test against an unpublished root validator change, create a temporary Go workspace containing the repository root and this submodule, as the repository's contrib CI job does. No application-specific schema or fixture is required.

Documentation

Overview

Package openapi generates OpenAPI 3.1 documents from Go request and response types, translating validate tags into JSON Schema constraints (min:3 on a string becomes minLength, in:a,b becomes enum, required populates the required list). Rules without a JSON Schema counterpart are skipped rather than approximated. A Generator accumulates operations and renders a Document or its JSON; DocsHTML serves a Scalar page for it.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidOption reports nil options or invalid option arguments, including
	// empty required text, nil schemas or invalid transforms, unsupported authentication,
	// undefined or empty security requirements, malformed examples, duplicate or
	// forbidden headers/parameters, and optional explicit path parameters.
	ErrInvalidOption = errors.New("openapi: invalid option")
	// ErrInvalidOperation reports an unusable Add call: an unknown method, a
	// relative path or one with a query or fragment, no response, a duplicate
	// response code or operation ID, a status outside 100..599, a missing explicit
	// path placeholder, or body metadata/examples on an operation without content.
	ErrInvalidOperation = errors.New("openapi: invalid operation")
	// ErrOperationExists reports an Add for a method and path already
	// registered.
	ErrOperationExists = errors.New("openapi: operation already exists")
)

Errors returned for invalid generator configuration and operations; they are wrapped, so match them with errors.Is.

Functions

func DocsHTML

func DocsHTML(title, specURL string) []byte

DocsHTML returns an HTML page that renders the OpenAPI document served at specURL with Scalar (https://github.com/scalar/scalar), loaded from the jsDelivr CDN. title and specURL are interpolated verbatim, so they must be trusted values, not user input.

Types

type APIKeyLocation added in v0.3.0

type APIKeyLocation string

APIKeyLocation selects the input carrying an API key.

const (
	HeaderLocation APIKeyLocation = "header"
	QueryLocation  APIKeyLocation = "query"
	CookieLocation APIKeyLocation = "cookie"
)

type Components

type Components struct {
	Schemas         map[string]*Schema         `json:"schemas,omitempty"`
	SecuritySchemes map[string]*SecurityScheme `json:"securitySchemes,omitempty"`
}

Components holds the named schemas referenced by $ref, one per named struct type reachable from the registered operations.

type Document

type Document struct {
	OpenAPI    string                `json:"openapi"`
	Info       Info                  `json:"info"`
	Paths      map[string]PathItem   `json:"paths,omitempty"`
	Components *Components           `json:"components,omitempty"`
	Servers    []Server              `json:"servers,omitempty"`
	Security   []SecurityRequirement `json:"security,omitzero"`
}

Document is the generated OpenAPI 3.1 document, the subset of the specification the Generator emits. It marshals with encoding/json.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator accumulates operations and the component schemas they reference. Schema names are allocated on first use and kept stable; distinct types that flatten to the same name get numeric suffixes. It is not safe for concurrent use.

Example (Documentation)
package main

import (
	"fmt"
	"net/http"

	"github.com/libtnb/validator/contrib/openapi"
)

func main() {
	type createProduct struct {
		Name  string `json:"name" validate:"required" openapi:"description=Product name,example=Notebook"`
		OldID string `json:"oldId" openapi:"description='Compatibility identifier, use id instead',deprecated"`
	}
	type product struct {
		ID int `json:"id" openapi:"description=Product ID,example=42,readOnly"`
	}
	g := openapi.MustNew("Catalog", "1.0.0",
		openapi.WithSecurityScheme("apiKey", openapi.APIKeyScheme("X-API-Key", openapi.HeaderLocation)),
		openapi.WithDefaultSecurity(openapi.SecurityRequirement{"apiKey"}),
	)
	err := g.Add[createProduct](http.MethodPost, "/products",
		openapi.WithOperationID("createProduct"), openapi.WithDescription("Create a product."),
		openapi.WithRequestExample(createProduct{Name: "Notebook"}),
		openapi.WithResponse[product](http.StatusCreated, openapi.ResponseExample(product{ID: 42})),
	)
	if err != nil {
		panic(err)
	}
	operation := g.Document().Paths["/products"]["post"]
	properties := operation.RequestBody.Content["application/json"].Schema.Properties
	fmt.Println(operation.OperationID)
	fmt.Println(properties["name"].Description)
	fmt.Println(properties["oldId"].Deprecated)
	fmt.Println(string(operation.Responses["201"].Content["application/json"].Example))
}
Output:
createProduct
Product name
true
{"id":42}

func MustNew added in v0.2.1

func MustNew(title, version string, opts ...Option) *Generator

MustNew is New with panic-on-error semantics.

func New

func New(title, version string, opts ...Option) (*Generator, error)

New constructs a Generator for an API with the given title and version. Returns ErrInvalidOption when either is blank or an option fails.

func (*Generator) Add

func (g *Generator) Add[Request any](method, path string, opts ...OperationOption) error

Add registers an operation for method and path. Request describes the input: fields tagged uri become path parameters, fields tagged query become query parameters (required when their rules say so), and for POST, PUT and PATCH the remaining json-visible fields form the request body; use NoBody for none. At least one WithResponse or WithDefaultResponse option is required. Generation is transactional: on error, paths, components and schema-name allocation are unchanged.

Returns ErrInvalidOperation for a bad method, path or response set, ErrOperationExists when the method and path are already registered, ErrInvalidOption for invalid option arguments (including security references), and a wrapped contextual error when a type's validate/openapi tags or schema transform fail. Documentation tags do not constitute generator options.

func (*Generator) Document

func (g *Generator) Document() Document

Document returns a deep copy of the document built so far, so callers can post-process it without affecting later Add calls.

func (*Generator) JSON

func (g *Generator) JSON() ([]byte, error)

JSON renders the document as indented JSON with sorted map keys, so the output is byte-stable across runs and suitable for committing.

type Header struct {
	Description string         `json:"description,omitempty"`
	Required    bool           `json:"required,omitempty,omitzero"`
	Schema      *Schema        `json:"schema,omitempty"`
	Example     jsontext.Value `json:"example,omitzero"`
}

Header describes a response header, whose name is the key in Response.Headers.

type Info

type Info struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

Info identifies the API by the title and version given to New.

type MediaType

type MediaType struct {
	Schema *Schema `json:"schema,omitempty"`
	// Nil omits the example; jsontext.Value("null") emits an explicit JSON null.
	Example jsontext.Value `json:"example,omitzero"`
}

MediaType associates a content type entry with its schema.

type NoBody added in v0.2.1

type NoBody struct{}

NoBody is the type argument for an operation without a JSON request body or for a response without content, such as 204.

type Operation

type Operation struct {
	OperationID string `json:"operationId,omitempty"`
	Description string `json:"description,omitempty"`
	Deprecated  bool   `json:"deprecated,omitempty,omitzero"`
	// Nil inherits document security; a non-nil empty slice disables it.
	Security    []SecurityRequirement `json:"security,omitzero"`
	Summary     string                `json:"summary,omitempty,omitzero"`
	Tags        []string              `json:"tags,omitempty"`
	Parameters  []*Parameter          `json:"parameters,omitempty"`
	RequestBody *RequestBody          `json:"requestBody,omitempty"`
	Responses   map[string]*Response  `json:"responses"`
}

Operation describes one HTTP operation: its parameters, optional request body and responses keyed by status code or "default".

type OperationOption added in v0.2.1

type OperationOption func(*operationConfig) error

OperationOption configures one Add call.

func Deprecated added in v0.3.0

func Deprecated() OperationOption

Deprecated marks an operation as deprecated without removing it.

func RequestOptional added in v0.3.0

func RequestOptional() OperationOption

RequestOptional allows omitting the generated request body, even when some of its properties are required if a body is supplied.

func RequestRequired added in v0.3.0

func RequestRequired() OperationOption

RequestRequired marks the generated request body as required without changing property requirements or the server's runtime validation.

func WithDefaultResponse added in v0.2.1

func WithDefaultResponse[Body any](opts ...ResponseOption) OperationOption

WithDefaultResponse adds the OpenAPI "default" response, used for any status not listed explicitly; Body follows the WithResponse rules.

func WithDescription added in v0.3.0

func WithDescription(description string) OperationOption

WithDescription sets the operation's description.

func WithOperationID added in v0.3.0

func WithOperationID(id string) OperationOption

WithOperationID sets a nonblank operation identifier. An ID must be unique within the document; it is not derived from a handler or URL.

func WithParameter added in v0.3.0

func WithParameter(parameter Parameter) OperationOption

WithParameter adds a typed parameter or replaces the inferred parameter with the same (in, name). Replacement is complete, including its schema and required flag. Path parameters must be required. Repeated explicit parameters are errors.

func WithRequestDescription added in v0.3.0

func WithRequestDescription(description string) OperationOption

WithRequestDescription describes the JSON request body. It is an error to use this option when the operation has no generated body.

func WithRequestExample added in v0.3.0

func WithRequestExample(value any) OperationOption

WithRequestExample snapshots a JSON request example, including an explicit nil (JSON null). Invalid JSON values and operations without a body are errors.

func WithResponse added in v0.2.1

func WithResponse[Body any](status int, opts ...ResponseOption) OperationOption

WithResponse adds a response for an HTTP status whose JSON body is Body; use NoBody for a response without content. A status outside 100..599 or a code declared twice on one operation is ErrInvalidOperation at Add.

func WithSecurity added in v0.3.0

func WithSecurity(first SecurityRequirement, alternatives ...SecurityRequirement) OperationOption

WithSecurity overrides document authentication for an operation. At least one nonempty requirement is mandatory; use WithoutSecurity for a public operation.

func WithSummary added in v0.2.1

func WithSummary(summary string) OperationOption

WithSummary sets the operation summary, trimmed of surrounding whitespace.

func WithTags added in v0.2.1

func WithTags(tags ...string) OperationOption

WithTags appends operation tags, trimmed; a blank tag is ErrInvalidOption.

func WithoutSecurity added in v0.3.0

func WithoutSecurity() OperationOption

WithoutSecurity explicitly makes an operation public in the document by emitting security: [], overriding any document-wide requirements.

type Option

type Option func(*Generator) error

Option configures a Generator during New; the first error aborts construction.

func WithDefaultSecurity added in v0.3.0

func WithDefaultSecurity(first SecurityRequirement, alternatives ...SecurityRequirement) Option

WithDefaultSecurity sets document-wide authentication requirements. Each requirement combines schemes with AND; separate requirements are alternatives.

func WithInfoDescription added in v0.3.0

func WithInfoDescription(description string) Option

WithInfoDescription sets the API's overall description.

func WithSchema added in v0.2.1

func WithSchema[T any](schema *Schema) Option

WithSchema replaces the schema inferred for T (pointer layers ignored) wherever T appears, for types whose wire format reflection cannot see. The schema is deep-copied. A nil schema or T being NoBody is ErrInvalidOption.

func WithSchemaTransform added in v0.3.0

func WithSchemaTransform[T any](transform func(*Schema) error) Option

WithSchemaTransform changes a named Go type's inferred schema without replacing its generated fields. Built-in and anonymous types are rejected; use WithSchema for scalar wire formats. It runs each time a schema is inferred: once for a named struct component, per operation for a request body, and per occurrence for any inline named type or custom marshaler. It receives the inferred type schema before field-specific rules and tags are added. A struct schema already contains its children's rules and tags. A top-level request is transformed after its body fields have been generated, excluding path/query parameters. WithSchema takes precedence over transforms. The callback must not retain or mutate the schema after returning. Errors abort Add without committing any generated state.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/libtnb/validator/contrib/openapi"
)

func main() {
	type contact struct {
		Email string `json:"email" openapi:"description=Email address"`
		Phone string `json:"phone" openapi:"description=Phone number"`
	}
	g := openapi.MustNew("Contacts", "1.0.0", openapi.WithSchemaTransform[contact](func(schema *openapi.Schema) error {
		schema.AnyOf = []*openapi.Schema{{Required: []string{"email"}}, {Required: []string{"phone"}}}
		return nil
	}))
	if err := g.Add[contact](http.MethodPost, "/contacts", openapi.RequestRequired(), openapi.WithResponse[openapi.NoBody](204)); err != nil {
		panic(err)
	}
	body := g.Document().Paths["/contacts"]["post"].RequestBody
	fmt.Println(body.Required)
	fmt.Println(len(body.Content["application/json"].Schema.Properties))
	fmt.Println(len(body.Content["application/json"].Schema.AnyOf))
}
Output:
true
2
2

func WithSecurityScheme added in v0.3.0

func WithSecurityScheme(name string, scheme SecurityScheme) Option

WithSecurityScheme registers API key or HTTP authentication by name. Duplicate names and incomplete schemes are errors. Requirement references are checked after New's options have all been applied, so option order does not matter.

func WithServer added in v0.3.0

func WithServer(url, description string) Option

WithServer appends an API base URL. Relative URLs are allowed by OpenAPI.

func WithValidator

func WithValidator(v *validator.Validator) Option

WithValidator selects the Validator whose tag name, naming function and rule registry are used to inspect validate tags; the default is validator.Default. A nil v is ErrInvalidOption.

type Parameter

type Parameter struct {
	Name        string         `json:"name"`
	In          string         `json:"in"` // "path", "query", "header", or "cookie"
	Required    bool           `json:"required,omitempty,omitzero"`
	Schema      *Schema        `json:"schema,omitempty"`
	Description string         `json:"description,omitempty"`
	Deprecated  bool           `json:"deprecated,omitempty,omitzero"`
	Example     jsontext.Value `json:"example,omitzero"`
}

Parameter describes an inferred uri/query input or an explicitly declared path, query, header, or cookie input. Path parameters are always required.

type PathItem

type PathItem map[string]*Operation

PathItem maps a lowercase HTTP method ("get", "post", ...) to its operation.

type RequestBody

type RequestBody struct {
	Description string                `json:"description,omitempty"`
	Required    bool                  `json:"required,omitempty,omitzero"`
	Content     map[string]*MediaType `json:"content"`
}

RequestBody describes a JSON request body; Required is set when any body property is required.

type Response

type Response struct {
	Description string                `json:"description"`
	Content     map[string]*MediaType `json:"content,omitempty"`
	Headers     map[string]*Header    `json:"headers,omitempty"`
}

Response describes one HTTP response; Content is nil for NoBody.

type ResponseOption added in v0.2.1

type ResponseOption func(*responseOptions) error

ResponseOption configures one WithResponse or WithDefaultResponse entry.

func ResponseDescription added in v0.2.1

func ResponseDescription(description string) ResponseOption

ResponseDescription overrides the response description, which defaults to the HTTP status text ("Created") or "Response" for the default response. A blank description is ErrInvalidOption.

func ResponseExample added in v0.3.0

func ResponseExample(value any) ResponseOption

ResponseExample snapshots the response's JSON example. Passing nil emits example: null; omitting this option emits no example. NoBody cannot have one.

func ResponseHeader added in v0.3.0

func ResponseHeader(name string, header Header) ResponseOption

ResponseHeader documents a response header. Names are compared without case; repeated names are errors. Content-Type is described through response content.

type Schema

type Schema struct {
	Ref                  string             `json:"$ref,omitempty,omitzero"`
	Type                 string             `json:"type,omitempty,omitzero"`
	Format               string             `json:"format,omitempty,omitzero"`
	Description          string             `json:"description,omitempty,omitzero"`
	Example              jsontext.Value     `json:"example,omitzero"`
	Default              jsontext.Value     `json:"default,omitzero"`
	Const                jsontext.Value     `json:"const,omitzero"`
	Deprecated           bool               `json:"deprecated,omitempty,omitzero"`
	ReadOnly             bool               `json:"readOnly,omitempty,omitzero"`
	WriteOnly            bool               `json:"writeOnly,omitempty,omitzero"`
	AllOf                []*Schema          `json:"allOf,omitempty"`
	AnyOf                []*Schema          `json:"anyOf,omitempty"`
	OneOf                []*Schema          `json:"oneOf,omitempty"`
	Not                  *Schema            `json:"not,omitempty"`
	Properties           map[string]*Schema `json:"properties,omitempty"`
	Items                *Schema            `json:"items,omitempty"`
	AdditionalProperties *Schema            `json:"additionalProperties,omitempty"`
	Required             []string           `json:"required,omitempty"`
	Enum                 []any              `json:"enum,omitempty"`
	Pattern              string             `json:"pattern,omitempty,omitzero"`
	Minimum              *float64           `json:"minimum,omitempty"`
	Maximum              *float64           `json:"maximum,omitempty"`
	ExclusiveMinimum     *float64           `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum     *float64           `json:"exclusiveMaximum,omitempty"`
	MinLength            *uint64            `json:"minLength,omitempty"`
	MaxLength            *uint64            `json:"maxLength,omitempty"`
	MinItems             *uint64            `json:"minItems,omitempty"`
	MaxItems             *uint64            `json:"maxItems,omitempty"`
	UniqueItems          bool               `json:"uniqueItems,omitempty,omitzero"`
	// ContentEncoding marks base64 payloads ([]byte fields), per JSON Schema 2020-12.
	ContentEncoding string `json:"contentEncoding,omitempty,omitzero"`
}

Schema is the JSON Schema subset used for parameters, bodies and components. Numeric bounds are pointers so that zero is distinguishable from unset.

type SecurityRequirement added in v0.3.0

type SecurityRequirement []string

SecurityRequirement combines named schemes with AND. Multiple requirements in a security array are alternatives (OR). Only supported, scope-free schemes can be required. WithSecurity rejects empty requirements.

func (SecurityRequirement) MarshalJSON added in v0.3.0

func (requirement SecurityRequirement) MarshalJSON() ([]byte, error)

MarshalJSON encodes supported scheme references using OpenAPI's empty scope arrays.

type SecurityScheme added in v0.3.0

type SecurityScheme struct {
	Description string
	// contains filtered or unexported fields
}

SecurityScheme describes API key or HTTP authentication. The generator does not perform authentication; it documents the server's requirements.

func APIKeyScheme added in v0.3.0

func APIKeyScheme(name string, location APIKeyLocation) SecurityScheme

APIKeyScheme describes an API key passed in a header, query, or cookie. WithSecurityScheme validates the name and location when registering it.

func HTTPScheme added in v0.3.0

func HTTPScheme(scheme, bearerFormat string) SecurityScheme

HTTPScheme describes HTTP authentication, such as basic or bearer. The bearer format is optional and is valid only for the bearer scheme.

func (SecurityScheme) MarshalJSON added in v0.3.0

func (scheme SecurityScheme) MarshalJSON() ([]byte, error)

MarshalJSON renders a scheme created with APIKeyScheme or HTTPScheme.

type Server added in v0.3.0

type Server struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

Server is a base URL at which the API is available.

Jump to

Keyboard shortcuts

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