openapi

package
v4.8.1 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package openapi provides a fluent, dependency-free builder for OpenAPI 3.1 specifications. It is designed for CQRS/HTTP libraries like cqrs-htmx whose endpoints are registered on a consumer-owned router: because the library cannot introspect the consumer's paths, this package lets the consumer (or a code generator) declare the spec explicitly and serialize it to valid OpenAPI 3.1 JSON in one call.

Quick start

spec := openapi.New("My API", "1.0.0").
	Path("/items",
		openapi.Post("CreateItem").
			Summary("Create a new item").
			Tag("items").
			JSONBody(openapi.Object(
				openapi.Prop("name", openapi.String().MinLength(1)),
			)).
			Response(201, "Created"),
	).
	Path("/items/{id}",
		openapi.Get("GetItem").
			PathParam("id", openapi.String(), "the item id").
			Response(200, "OK", openapi.JSON(
				openapi.Object(openapi.Prop("id", openapi.String())),
			)),
	)

data, err := spec.JSON()

cqrs-htmx integration

Attach metadata to an [cqrshtmx.App] handler with the WithOpenAPI option (see options_openapi.go in the root package), then assemble the spec from your route table. The openapi package itself has no dependency on the root package and can be used standalone.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Delete

func Delete(operationID string) *opBuilder

Delete starts a DELETE operation with the given operationId.

func False

func False() any

False returns a sentinel usable as AdditionalProperties to forbid any unmapped object property.

func Get

func Get(operationID string) *opBuilder

Get starts a GET operation with the given operationId.

func Head(operationID string) *opBuilder

Head starts a HEAD operation with the given operationId.

func Options

func Options(operationID string) *opBuilder

Options starts an OPTIONS operation with the given operationId.

func Patch

func Patch(operationID string) *opBuilder

Patch starts a PATCH operation with the given operationId.

func Post

func Post(operationID string) *opBuilder

Post starts a POST operation with the given operationId.

func Put

func Put(operationID string) *opBuilder

Put starts a PUT operation with the given operationId.

Types

type Components

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

Components holds reusable schemas referenced via $ref.

type Info

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

Info describes the API metadata.

type MediaType

type MediaType struct {
	Schema *Schema `json:"schema,omitempty"`
}

MediaType pairs a content type with a schema (e.g. application/json).

func JSON

func JSON(schema *Schema) *MediaType

JSON wraps a schema in an application/json MediaType, for use as a response or request body content entry.

type Operation

type Operation struct {
	Tags        []string          `json:"tags,omitempty"`
	Summary     string            `json:"summary,omitempty"`
	Description string            `json:"description,omitempty"`
	OperationID string            `json:"operationId,omitempty"`
	Parameters  []Parameter       `json:"parameters,omitempty"`
	RequestBody *RequestBody      `json:"requestBody,omitempty"`
	Responses   map[int]*Response `json:"responses"`
	Deprecated  omitBool          `json:"deprecated,omitempty"`
}

Operation describes a single HTTP operation on a path.

type Parameter

type Parameter struct {
	Name        string   `json:"name"`
	In          string   `json:"in"`
	Description string   `json:"description,omitempty"`
	Required    omitBool `json:"required,omitempty"`
	Schema      *Schema  `json:"schema,omitempty"`
}

Parameter is a path, query, header, or cookie parameter.

type PathItem

type PathItem struct {
	Summary     string      `json:"summary,omitempty"`
	Description string      `json:"description,omitempty"`
	Get         *Operation  `json:"get,omitempty"`
	Post        *Operation  `json:"post,omitempty"`
	Put         *Operation  `json:"put,omitempty"`
	Patch       *Operation  `json:"patch,omitempty"`
	Delete      *Operation  `json:"delete,omitempty"`
	Head        *Operation  `json:"head,omitempty"`
	Options     *Operation  `json:"options,omitempty"`
	Parameters  []Parameter `json:"parameters,omitempty"`
}

PathItem describes the operations available on a single path.

type Property

type Property struct {
	Name     string
	Schema   *Schema
	Required bool
}

Property is a name+schema pair, optionally required, used by Object.

func Prop

func Prop(name string, schema *Schema) Property

Prop builds an optional object property.

func PropReq

func PropReq(name string, schema *Schema) Property

PropReq builds a required object property.

type RequestBody

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

RequestBody describes the expected request body.

type Response

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

Response describes a single HTTP response by status code.

type Schema

type Schema struct {
	// Type is the JSON Schema type: "string", "integer", "number", "boolean",
	// "object", "array", or "null".
	Type string `json:"type,omitempty"`

	// Format restricts a type further: "int64", "uuid", "date-time", "email",
	// "byte" (base64), "uri", etc. OpenAPI defines a standard set; consumers
	// may use any string.
	Format string `json:"format,omitempty"`

	// Description is a human-readable description.
	Description string `json:"description,omitempty"`

	// Properties maps object property names to their schemas. Only meaningful
	// when Type == "object".
	Properties map[string]*Schema `json:"properties,omitempty"`

	// Required lists property names that must be present. Only meaningful when
	// Type == "object".
	Required []string `json:"required,omitempty"`

	// Items is the schema for array elements. Only meaningful when
	// Type == "array".
	Items *Schema `json:"items,omitempty"`

	// Enum constrains the value to one of the listed constants (any JSON type).
	Enum []any `json:"enum,omitempty"`

	// MinLength is the minimum string length (string type only).
	MinLength *int `json:"minLength,omitempty"`

	// MaxLength is the maximum string length (string type only).
	MaxLength *int `json:"maxLength,omitempty"`

	// Minimum is the inclusive numeric minimum (number/integer type only).
	Minimum *float64 `json:"minimum,omitempty"`

	// Maximum is the inclusive numeric maximum (number/integer type only).
	Maximum *float64 `json:"maximum,omitempty"`

	// AdditionalProperties controls unmapped object keys. Pass a *Schema to
	// constrain their type, or openapi.False() to forbid them entirely.
	AdditionalProperties any `json:"additionalProperties,omitempty"`

	// Ref is a JSON reference ($ref) into the components/schemas map, e.g.
	// "#/components/schemas/Item". Use Ref(name) to construct one. When set,
	// all other fields are ignored on serialization (per JSON Reference).
	Ref string `json:"$ref,omitempty"`
}

Schema is a subset of JSON Schema (draft 2020-12) sufficient for OpenAPI 3.1 request bodies, parameters, and responses. All fields are optional and omitted from the serialized output when zero.

Construct schemas with the helper constructors (String, Object, Array, etc.) rather than struct literals — the helpers set the Type field consistently and are far more readable.

func Array

func Array(items *Schema) *Schema

Array returns a schema with type "array" and the given item schema.

func Boolean

func Boolean() *Schema

Boolean returns a schema with type "boolean".

func ErrorSchema

func ErrorSchema() *Schema

ErrorSchema returns a standard RFC 7807-style problem-details object schema, convenient for error responses.

func FreeForm

func FreeForm() *Schema

FreeForm returns an object schema that allows any properties (empty object). Useful for "any JSON" payloads.

func Integer

func Integer() *Schema

Integer returns a schema with type "integer".

func Number

func Number() *Schema

Number returns a schema with type "number".

func Object

func Object(properties ...Property) *Schema

Object returns a schema with type "object" and the given properties. Use Prop to build each property.

func Ref

func Ref(name string) *Schema

Ref returns a schema that references a named schema in components/schemas. The argument is the schema name (NOT the full "#/components/schemas/..." path); the path prefix is added automatically.

func String

func String() *Schema

String returns a schema with type "string".

func (*Schema) WithDescription

func (s *Schema) WithDescription(desc string) *Schema

WithDescription sets the description and returns the schema.

func (*Schema) WithEnum

func (s *Schema) WithEnum(values ...any) *Schema

WithEnum constrains the value to the given constants and returns the schema.

func (*Schema) WithFormat

func (s *Schema) WithFormat(format string) *Schema

WithFormat sets the format and returns the schema.

func (*Schema) WithMax

func (s *Schema) WithMax(n float64) *Schema

WithMax sets the inclusive numeric maximum and returns the schema.

func (*Schema) WithMaxLength

func (s *Schema) WithMaxLength(n int) *Schema

WithMaxLength sets maxLength (string type) and returns the schema.

func (*Schema) WithMin

func (s *Schema) WithMin(n float64) *Schema

WithMin sets the inclusive numeric minimum and returns the schema.

func (*Schema) WithMinLength

func (s *Schema) WithMinLength(n int) *Schema

WithMinLength sets minLength (string type) and returns the schema.

type Spec

type Spec struct {
	OpenAPI    string               `json:"openapi"`
	Info       Info                 `json:"info"`
	Paths      map[string]*PathItem `json:"paths"`
	Components *Components          `json:"components,omitempty"`
}

Spec is the root OpenAPI 3.1 document. Construct one with New, then add paths and (optionally) reusable component schemas. Serialize with JSON.

func New

func New(title, version string) *Spec

New creates a Spec rooted at OpenAPI 3.1.0 with the given title and version, and an empty paths map ready to receive operations.

func (*Spec) JSON

func (s *Spec) JSON() ([]byte, error)

JSON serializes the spec to indented OpenAPI 3.1 JSON. The output is suitable for writing to an openapi.json file or serving from a /openapi.json endpoint.

func (*Spec) Path

func (s *Spec) Path(path string, operations ...*opBuilder) *Spec

Path registers operations on a path and returns the spec. Each operation (Get, Post, ...) is constructed with the Get/Post/... constructors. If the path already exists, operations are merged into the existing PathItem.

func (*Spec) Schema

func (s *Spec) Schema(name string, schema *Schema) *Spec

Schema registers a reusable component schema (referenced via Ref(name)) and returns the spec. This is the standard way to share a schema across multiple operations without inlining it everywhere.

func (*Spec) WithDescription

func (s *Spec) WithDescription(desc string) *Spec

WithDescription sets the API description and returns the spec.

Jump to

Keyboard shortcuts

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