Documentation
¶
Overview ¶
Package openapi provides automatic OpenAPI v3.1.0 specification generation from mux router routes using Go reflection and struct tags.
The package targets the OpenAPI Specification v3.1.0 and uses JSON Schema Draft 2020-12 for schema generation. It produces a complete OpenAPI document from registered routes with zero external schema files.
See: https://spec.openapis.org/oas/v3.1.0 See: https://json-schema.org/draft/2020-12/json-schema-core See: https://json-schema.org/draft/2020-12/json-schema-validation
Spec Builder ¶
Create a spec, attach metadata to routes, and build the document:
spec := openapi.NewSpec(openapi.Info{Title: "My API", Version: "1.0.0"})
Variant B: Attach Metadata to Named Routes ¶
Use Op to annotate existing named routes:
r := mux.NewRouter()
r.HandleFunc("/users", listUsers).Methods(http.MethodGet).Name("listUsers")
r.HandleFunc("/users", createUser).Methods(http.MethodPost).Name("createUser")
spec.Op("listUsers").
Summary("List all users").
Tags("users").
Response(http.StatusOK, []User{})
spec.Op("createUser").
Summary("Create a user").
Tags("users").
Request(CreateUserInput{}).
Response(http.StatusCreated, User{})
Route: Attach Metadata to Any Mux Route ¶
Use Route to attach OpenAPI metadata to an already-configured mux route, preserving full mux flexibility (Methods, Headers, Queries, Schemes, etc.):
spec.Route(r.HandleFunc("/users", createUser).Methods(http.MethodPost)).
Summary("Create a user").
Tags("users").
Request(CreateUserInput{}).
Response(http.StatusCreated, User{})
Routes can use any mux.Route configuration:
spec.Route(r.HandleFunc("/users", listUsers).
Methods(http.MethodGet).
Headers("Accept", "application/json")).
Summary("List users").
Response(http.StatusOK, []User{})
Route Groups ¶
Use Group to apply shared OpenAPI metadata defaults to a logical group of operations. Groups are a metadata concept only -- they do not affect routing. Routes created through a group inherit the group's tags, security, servers, parameters, responses, and external docs.
users := spec.Group().
Tags("users").
Security(openapi.SecurityRequirement{"basic": {}}).
Response(http.StatusForbidden, ErrorResponse{}).
Response(http.StatusNotFound, ErrorResponse{})
users.Route(r.HandleFunc("/users", listUsers).Methods(http.MethodGet)).
Summary("List users").
Response(http.StatusOK, []User{})
users.Route(r.HandleFunc("/users", createUser).Methods(http.MethodPost)).
Summary("Create user").
Request(CreateUserInput{}).
Response(http.StatusCreated, User{})
Both routes above automatically include 403 and 404 responses from the group.
Groups support the full response builder API: Response, ResponseContent, ResponseDescription, ResponseHeader, ResponseLink, DefaultResponse, DefaultResponseDescription, and DefaultResponseHeader. For example:
spec.Group().
Response(http.StatusForbidden, ErrorResponse{}).
ResponseContent(http.StatusForbidden, "application/xml", ErrorResponse{}).
ResponseDescription(http.StatusForbidden, "Insufficient permissions").
DefaultResponse(ErrorResponse{}).
DefaultResponseHeader("X-Request-ID", &openapi.Header{
Schema: &openapi.Schema{Type: openapi.TypeString("string")},
})
Override/merge semantics per field:
- Tags: append (group tags + operation tags combined)
- Security: replace (operation-level Security call overrides group value)
- Deprecated: one-way latch (group deprecation cannot be undone per-operation)
- Servers: append (group servers + operation servers combined)
- Parameters: append (group parameters + operation parameters combined)
- Responses: merge (group responses + operation responses; operation overrides per status code)
- ExternalDocs: replace (operation-level ExternalDocs call overrides group value)
Groups also support Op for named routes:
users.Op("listUsers").Summary("List users")
Security ¶
Register security schemes and apply them at document or operation level:
spec.AddSecurityScheme("bearerAuth", &openapi.SecurityScheme{
Type: "http",
Scheme: "bearer",
BearerFormat: "JWT",
})
spec.SetSecurity(openapi.SecurityRequirement{"bearerAuth": {}})
Override security per operation (empty Security() marks an endpoint as public):
spec.Route(r.HandleFunc("/health", healthHandler).Methods(http.MethodGet)).
Summary("Health check").
Security()
External Documentation ¶
Attach external docs at the document level:
spec.SetExternalDocs("https://docs.example.com", "Full documentation")
Or at the operation level:
spec.Op("listUsers").ExternalDocs("https://docs.example.com/users", "User API docs")
Tags ¶
Tags used in operations are automatically collected into the document-level tags list, sorted alphabetically. Use AddTag to provide descriptions and external documentation for tags:
spec.AddTag(openapi.Tag{
Name: "users",
Description: "User management operations",
ExternalDocs: &openapi.ExternalDocs{URL: "https://docs.example.com/users"},
})
User-defined tags take precedence over auto-collected tags. Tags defined via AddTag but not used by any operation are still included in the output.
Reusable Components ¶
Register reusable objects in components:
spec.AddComponentResponse("NotFound", &openapi.Response{Description: "Not found"})
spec.AddComponentParameter("pageParam", &openapi.Parameter{Name: "page", In: "query"})
spec.AddComponentExample("sample", &openapi.Example{Summary: "A sample", Value: "test"})
spec.AddComponentRequestBody("CreatePet", &openapi.RequestBody{Description: "Pet to create"})
spec.AddComponentHeader("X-Rate-Limit", &openapi.Header{Schema: &openapi.Schema{Type: openapi.TypeString("integer")}})
spec.AddComponentLink("GetUser", &openapi.Link{OperationID: "getUser"})
Path-Level Metadata ¶
Set summary, description, and shared parameters on a path. These apply to all operations under the path:
spec.SetPathSummary("/users/{id}", "Represents a user")
spec.SetPathDescription("/users/{id}", "Individual user identified by ID.")
spec.AddPathParameter("/users/{id}", &openapi.Parameter{
Name: "X-Tenant-ID", In: "header",
Schema: &openapi.Schema{Type: openapi.TypeString("string")},
})
Server Overrides ¶
Servers can be overridden at the path or operation level. Path-level servers apply to all operations under a path, while operation-level servers apply to a single operation:
// Path-level: all operations under /files use the file server.
spec.AddPathServer("/files", openapi.Server{URL: "https://files.example.com"})
// Operation-level: only this operation uses the upload server.
spec.Op("upload").Server(openapi.Server{URL: "https://upload.example.com"})
Servers support URL template variables with enum and default values:
spec.AddServer(openapi.Server{
URL: "https://{environment}.example.com/v2",
Variables: map[string]*openapi.ServerVariable{
"environment": {
Default: "api",
Enum: []string{"api", "api.dev", "api.staging"},
},
},
})
Media Types ¶
Request and Response are JSON shortcuts. Use RequestContent and ResponseContent for any content type:
// JSON (default)
spec.Op("create").Request(Employee{}).Response(http.StatusOK, Employee{})
// XML
spec.Op("create").RequestContent("application/xml", Employee{})
// Multiple content types for the same operation
spec.Op("get").
Response(http.StatusOK, Employee{}).
ResponseContent(http.StatusOK, "application/xml", Employee{})
// Binary file upload
spec.Op("upload").RequestContent("application/octet-stream", &openapi.Schema{
Type: openapi.TypeString("string"), Format: "binary",
})
// Image response
spec.Op("avatar").ResponseContent(http.StatusOK, "image/png", &openapi.Schema{
Type: openapi.TypeString("string"), Format: "binary",
})
// Form data
spec.Op("submit").RequestContent("multipart/form-data", FormInput{})
Pass a *Schema directly for explicit schema control (binary, text, etc.) or a Go type for automatic schema generation via reflection.
Request Body Metadata ¶
Set description and required flag on request bodies:
spec.Op("create").
Request(CreateInput{}).
RequestDescription("The resource to create").
RequestRequired(false)
By default, request bodies are required (true).
Default Response ¶
Use DefaultResponse to define a catch-all response for status codes not covered by specific responses:
spec.Op("getUser").
Response(http.StatusOK, User{}).
DefaultResponse(ErrorResponse{})
DefaultResponseContent works like ResponseContent for custom content types.
Response Headers and Links ¶
Add headers and links to responses:
spec.Op("listUsers").
Response(http.StatusOK, []User{}).
ResponseHeader(http.StatusOK, "X-Total-Count", &openapi.Header{
Description: "Total number of users",
Schema: &openapi.Schema{Type: openapi.TypeString("integer")},
}).
ResponseLink(http.StatusOK, "GetNext", &openapi.Link{
OperationID: "listUsers",
Parameters: map[string]any{"page": "$response.body#/nextPage"},
})
Operation ID ¶
When using Op, the route name becomes the operationId automatically. When using Route, the mux route name is used if set. Use OperationID to set or override the operation ID explicitly:
spec.Route(r.HandleFunc("/users", listUsers).Methods(http.MethodGet)).
OperationID("listAllUsers").
Summary("List users")
Response Descriptions ¶
Response descriptions are auto-generated from HTTP status text. Override them per status code:
spec.Op("getUser").
Response(http.StatusOK, User{}).
ResponseDescription(http.StatusOK, "The requested user").
DefaultResponse(ErrorResponse{}).
DefaultResponseDescription("Unexpected error")
Webhooks ¶
Webhooks describe API-initiated callbacks not tied to a specific path on the mux router:
spec.Webhook("newUser", http.MethodPost).
Summary("New user notification").
Request(UserEvent{}).
Response(http.StatusOK, nil)
Group defaults also apply to webhooks:
events := spec.Group().Tags("events")
events.Webhook("userCreated", http.MethodPost).Summary("User created")
Operation Extensions ¶
Operations support callbacks:
cb := openapi.Callback{"{$request.body#/callbackUrl}": &openapi.PathItem{...}}
spec.Op("subscribe").Callback("onEvent", &cb)
Struct Tags ¶
Use the "openapi" struct tag to enrich JSON Schema output:
type CreateUserInput struct {
Name string `json:"name" openapi:"description=User name,minLength=1,maxLength=100"`
Email string `json:"email" openapi:"format=email"`
Age int `json:"age,omitempty" openapi:"minimum=0,maximum=150"`
Role string `json:"role" openapi:"enum=admin|user|guest"`
}
Supported tag keys: description, example, format, title, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minLength, maxLength, pattern, multipleOf, minItems, maxItems, uniqueItems, minProperties, maxProperties, const, enum (pipe-separated), deprecated, readOnly, writeOnly.
Path Parameter Typing ¶
Mux route macros are automatically mapped to OpenAPI types:
{id:uuid} -> type: string, format: uuid
{page:int} -> type: integer
{v:float} -> type: number
{d:date} -> type: string, format: date
{h:domain} -> type: string, format: hostname
JSON Schema Generation ¶
Go types are converted to JSON Schema via reflection:
- bool -> {type: "boolean"}
- int/uint variants -> {type: "integer"}
- float32/float64 -> {type: "number"}
- string -> {type: "string"}
- []byte -> {type: "string", format: "byte"}
- time.Time -> {type: "string", format: "date-time"}
- *T -> nullable type using type arrays (e.g., ["string", "null"])
- []T -> {type: "array", items: schema(T)}
- map[string]V -> {type: "object", additionalProperties: schema(V)}
- struct -> {type: "object", properties: {...}, required: [...]}
Named struct types are deduplicated into #/components/schemas/{TypeName} and referenced via $ref.
Type-Level Examples ¶
Implement the Exampler interface to provide a complete example value for a type's component schema:
func (User) OpenAPIExample() any {
return User{ID: "550e8400-...", Name: "Alice", Email: "[email protected]"}
}
The returned value is serialized as the "example" field on the component schema. This works alongside field-level examples set via struct tags.
Generic Response Wrappers ¶
Go generics work naturally with the schema generator. Each concrete instantiation produces a distinct component schema with a sanitized name:
type ResponseData[T any] struct {
Success bool `json:"success"`
Errors []string `json:"errors,omitempty"`
Result T `json:"result"`
}
spec.Op("getUser").Response(http.StatusOK, ResponseData[User]{})
// → schema "ResponseDataUser" with Result typed as $ref User
spec.Op("listUsers").Response(http.StatusOK, ResponseData[[]User]{})
// → schema "ResponseDataUserList" with Result typed as array of $ref User
Custom Schema Names ¶
Implement the Namer interface to override the default component schema name for a type. The returned string is used as the base name in the components/schemas map, with standard collision resolution still applied:
func (User) OpenAPIName() string {
return "UserAccount"
}
If OpenAPIName returns an empty string, the default name (the Go type name) is used as a fallback.
Schema-Only Document (No Server Required) ¶
Use SchemaGenerator.Document to produce a complete OpenAPI document from Go types without a mux router. This is useful for schema-only documentation, code generation tooling, or non-HTTP applications:
gen := openapi.NewSchemaGenerator()
gen.Generate(User{})
gen.Generate(Order{})
doc := gen.Document(openapi.Info{Title: "My API", Version: "1.0.0"})
jsonBytes, _ := doc.JSON()
yamlBytes, _ := doc.YAML()
Parsing Documents ¶
Use DocumentFromJSON or DocumentFromYAML to parse existing OpenAPI documents from serialized form:
doc, err := openapi.DocumentFromJSON(jsonBytes) doc, err := openapi.DocumentFromYAML(yamlBytes)
Merging Documents ¶
MergeDocuments combines multiple OpenAPI documents into a single unified document. This is useful when different services each produce their own spec and you need a combined view:
merged, err := openapi.MergeDocuments(
openapi.Info{Title: "Platform API", Version: "1.0.0"},
usersDoc,
billingDoc,
)
Paths, webhooks, and all component types are merged. Duplicate entries with identical definitions are deduplicated; conflicts produce an error. Tags are deduplicated by name, security requirements are unioned, and source servers are dropped (set them on the returned document instead).
Serving the Specification ¶
Handle registers all OpenAPI endpoints under a base path. The config parameter is optional -- pass nil for defaults:
spec.Handle(r, "/swagger", nil)
This registers three routes:
/swagger/ - interactive HTML docs /swagger/schema.json - OpenAPI spec as JSON /swagger/schema.yaml - OpenAPI spec as YAML
Both /swagger and /swagger/ serve the docs UI. All handlers build the document once on first request using sync.Once.
Filenames are relative to the base path by default. Use an absolute path (starting with "/") to serve the schema at an independent location:
spec.Handle(r, "/swagger", &openapi.HandleConfig{
JSONFilename: "/api/v1/swagger.json",
YAMLFilename: "-",
})
// /swagger/ -> docs UI pointing to /api/v1/swagger.json
// /api/v1/swagger.json -> JSON spec
Choose the docs UI via HandleConfig:
openapi.DocsSwaggerUI (default) openapi.DocsRapiDoc openapi.DocsRedoc
Pass additional Swagger UI options via SwaggerUIConfig:
spec.Handle(r, "/swagger", &openapi.HandleConfig{
SwaggerUIConfig: map[string]any{
"docExpansion": "none",
"deepLinking": true,
},
})
Building the Document ¶
Build walks the mux router and assembles a complete *Document. This is called automatically by Handle, but can be used directly:
doc := spec.Build(r) data, _ := json.MarshalIndent(doc, "", " ")
Exporting to JSON or YAML ¶
Any *Document (from Build, SchemaGenerator.Document, DocumentFromJSON, DocumentFromYAML, or MergeDocuments) can be serialized to bytes:
doc := spec.Build(r) jsonBytes, _ := doc.JSON() // indented JSON yamlBytes, _ := doc.YAML() // YAML
This works for all document sources, including schema-only documents:
gen := openapi.NewSchemaGenerator()
gen.Generate(User{})
doc := gen.Document(openapi.Info{Title: "Schemas", Version: "1.0.0"})
data, _ := doc.JSON()
os.WriteFile("openapi.json", data, 0644)
And for merged documents:
merged, _ := openapi.MergeDocuments(info, usersDoc, billingDoc) data, _ := merged.YAML()
Subrouter Integration ¶
The openapi package works with mux subrouters. Build walks the entire router tree, so routes registered on subrouters appear with full paths:
api := r.PathPrefix("/api/v1").Subrouter()
spec.Route(api.HandleFunc("/users", listUsers).Methods(http.MethodGet)).
Summary("List users")
doc := spec.Build(r) // pass root router, not subrouter
Index ¶
- type Callback
- type Components
- type Contact
- type Discriminator
- type DocsUI
- type Document
- type Encoding
- type Example
- type Exampler
- type ExternalDocs
- type HandleConfig
- type Header
- type Info
- type License
- type Link
- type MediaType
- type Namer
- type OAuthFlow
- type OAuthFlows
- type Operation
- type OperationBuilder
- func (b *OperationBuilder) Callback(name string, cb *Callback) *OperationBuilder
- func (b *OperationBuilder) DefaultResponse(body any) *OperationBuilder
- func (b *OperationBuilder) DefaultResponseContent(contentType string, body any) *OperationBuilder
- func (b *OperationBuilder) DefaultResponseDescription(desc string) *OperationBuilder
- func (b *OperationBuilder) DefaultResponseHeader(name string, h *Header) *OperationBuilder
- func (b *OperationBuilder) DefaultResponseLink(name string, l *Link) *OperationBuilder
- func (b *OperationBuilder) Deprecated() *OperationBuilder
- func (b *OperationBuilder) Description(d string) *OperationBuilder
- func (b *OperationBuilder) ExternalDocs(url, description string) *OperationBuilder
- func (b *OperationBuilder) OperationID(id string) *OperationBuilder
- func (b *OperationBuilder) Parameter(param *Parameter) *OperationBuilder
- func (b *OperationBuilder) Request(body any) *OperationBuilder
- func (b *OperationBuilder) RequestContent(contentType string, body any) *OperationBuilder
- func (b *OperationBuilder) RequestDescription(desc string) *OperationBuilder
- func (b *OperationBuilder) RequestRequired(required bool) *OperationBuilder
- func (b *OperationBuilder) Response(statusCode int, body any) *OperationBuilder
- func (b *OperationBuilder) ResponseContent(statusCode int, contentType string, body any) *OperationBuilder
- func (b *OperationBuilder) ResponseDescription(statusCode int, desc string) *OperationBuilder
- func (b *OperationBuilder) ResponseHeader(statusCode int, name string, h *Header) *OperationBuilder
- func (b *OperationBuilder) ResponseLink(statusCode int, name string, l *Link) *OperationBuilder
- func (b *OperationBuilder) Security(reqs ...SecurityRequirement) *OperationBuilder
- func (b *OperationBuilder) Server(server Server) *OperationBuilder
- func (b *OperationBuilder) Summary(s string) *OperationBuilder
- func (b *OperationBuilder) Tags(tags ...string) *OperationBuilder
- type Parameter
- type PathItem
- type RequestBody
- type Response
- type RouteGroup
- func (g *RouteGroup) DefaultResponse(body any) *RouteGroup
- func (g *RouteGroup) DefaultResponseDescription(desc string) *RouteGroup
- func (g *RouteGroup) DefaultResponseHeader(name string, h *Header) *RouteGroup
- func (g *RouteGroup) Deprecated() *RouteGroup
- func (g *RouteGroup) ExternalDocs(url, description string) *RouteGroup
- func (g *RouteGroup) Op(routeName string) *OperationBuilder
- func (g *RouteGroup) Parameter(param *Parameter) *RouteGroup
- func (g *RouteGroup) Response(statusCode int, body any) *RouteGroup
- func (g *RouteGroup) ResponseContent(statusCode int, contentType string, body any) *RouteGroup
- func (g *RouteGroup) ResponseDescription(statusCode int, desc string) *RouteGroup
- func (g *RouteGroup) ResponseHeader(statusCode int, name string, h *Header) *RouteGroup
- func (g *RouteGroup) ResponseLink(statusCode int, name string, l *Link) *RouteGroup
- func (g *RouteGroup) Route(route *mux.Route) *OperationBuilder
- func (g *RouteGroup) Security(reqs ...SecurityRequirement) *RouteGroup
- func (g *RouteGroup) Server(server Server) *RouteGroup
- func (g *RouteGroup) Tags(tags ...string) *RouteGroup
- func (g *RouteGroup) Webhook(name, method string) *OperationBuilder
- type Schema
- type SchemaGenerator
- type SchemaType
- func (st SchemaType) IsEmpty() bool
- func (st SchemaType) IsZero() bool
- func (st SchemaType) MarshalJSON() ([]byte, error)
- func (st SchemaType) MarshalYAML() (any, error)
- func (st *SchemaType) UnmarshalJSON(data []byte) error
- func (st *SchemaType) UnmarshalYAML(node *yaml.Node) error
- func (st SchemaType) Values() []string
- type SecurityRequirement
- type SecurityScheme
- type Server
- type ServerVariable
- type Spec
- func (s *Spec) AddComponentCallback(name string, cb *Callback) *Spec
- func (s *Spec) AddComponentExample(name string, ex *Example) *Spec
- func (s *Spec) AddComponentHeader(name string, h *Header) *Spec
- func (s *Spec) AddComponentLink(name string, l *Link) *Spec
- func (s *Spec) AddComponentParameter(name string, param *Parameter) *Spec
- func (s *Spec) AddComponentPathItem(name string, pi *PathItem) *Spec
- func (s *Spec) AddComponentRequestBody(name string, rb *RequestBody) *Spec
- func (s *Spec) AddComponentResponse(name string, resp *Response) *Spec
- func (s *Spec) AddPathParameter(path string, param *Parameter) *Spec
- func (s *Spec) AddPathServer(path string, server Server) *Spec
- func (s *Spec) AddSecurityScheme(name string, scheme *SecurityScheme) *Spec
- func (s *Spec) AddServer(server Server) *Spec
- func (s *Spec) AddTag(tag Tag) *Spec
- func (s *Spec) Build(r *mux.Router) *Document
- func (s *Spec) Group() *RouteGroup
- func (s *Spec) Handle(r *mux.Router, basePath string, cfg *HandleConfig)
- func (s *Spec) Op(routeName string) *OperationBuilder
- func (s *Spec) Route(route *mux.Route) *OperationBuilder
- func (s *Spec) SetExternalDocs(url, description string) *Spec
- func (s *Spec) SetPathDescription(path, description string) *Spec
- func (s *Spec) SetPathSummary(path, summary string) *Spec
- func (s *Spec) SetSecurity(reqs ...SecurityRequirement) *Spec
- func (s *Spec) Webhook(name, method string) *OperationBuilder
- type Tag
- type XML
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Callback ¶
Callback is a map of runtime expressions to path items, describing requests that may be initiated by the API provider. The key expression is evaluated at runtime to identify the URL for the callback.
type Components ¶
type Components struct {
Schemas map[string]*Schema `json:"schemas,omitempty"`
Responses map[string]*Response `json:"responses,omitempty"`
Parameters map[string]*Parameter `json:"parameters,omitempty"`
Examples map[string]*Example `json:"examples,omitempty"`
RequestBodies map[string]*RequestBody `json:"requestBodies,omitempty"`
Headers map[string]*Header `json:"headers,omitempty"`
SecuritySchemes map[string]*SecurityScheme `json:"securitySchemes,omitempty"`
Links map[string]*Link `json:"links,omitempty"`
Callbacks map[string]*Callback `json:"callbacks,omitempty"`
PathItems map[string]*PathItem `json:"pathItems,omitempty"`
}
Components holds reusable OpenAPI objects. All objects defined within the Components Object have no effect on the API unless explicitly referenced from outside the Components Object.
type Contact ¶
type Contact struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
Contact represents contact information for the API.
type Discriminator ¶
type Discriminator struct {
PropertyName string `json:"propertyName"`
Mapping map[string]string `json:"mapping,omitempty"`
}
Discriminator aids in serialization, deserialization, and validation when request bodies or response payloads may be one of several schemas. Used with oneOf, anyOf, or allOf composition keywords.
See: https://spec.openapis.org/oas/v3.1.0#discriminator-object
type DocsUI ¶
type DocsUI int
DocsUI selects which interactive documentation UI to serve. The UI renders the OpenAPI Document as interactive HTML documentation.
type Document ¶
type Document struct {
OpenAPI string `json:"openapi"`
Info Info `json:"info"`
JSONSchemaDialect string `json:"jsonSchemaDialect,omitempty"`
Servers []Server `json:"servers,omitempty"`
Paths map[string]*PathItem `json:"paths,omitempty"`
Webhooks map[string]*PathItem `json:"webhooks,omitempty"`
Components *Components `json:"components,omitempty"`
Tags []Tag `json:"tags,omitempty"`
Security []SecurityRequirement `json:"security,omitempty"`
ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
}
Document represents the root of an OpenAPI v3.1.0 document.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object
func DocumentFromJSON ¶ added in v0.3.0
DocumentFromJSON parses a JSON-encoded OpenAPI document.
func DocumentFromYAML ¶ added in v0.3.0
DocumentFromYAML parses a YAML-encoded OpenAPI document.
func MergeDocuments ¶ added in v0.3.0
MergeDocuments combines multiple OpenAPI documents into a single document. The caller-provided Info is set on the result. Paths, webhooks, and all component maps are merged. Duplicate paths or webhooks produce a conflict error. Component entries with the same name are deduplicated when their normalized JSON representations are identical (string-only arrays such as "required" are sorted before comparison); differing entries produce a conflict error. Tags are deduplicated by name (first non-empty description wins) and sorted alphabetically. Security requirements are unioned and deduplicated (scope ordering is ignored). Servers from source documents are dropped.
All conflicts are collected and returned in a single error (not fail-fast).
type Encoding ¶
type Encoding struct {
ContentType string `json:"contentType,omitempty"`
Headers map[string]*Header `json:"headers,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
AllowReserved bool `json:"allowReserved,omitempty"`
}
Encoding describes encoding for a single property in a media type. Only applies to Request Body Objects when the media type is "multipart" or "application/x-www-form-urlencoded".
type Example ¶
type Example struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Value any `json:"value,omitempty"`
ExternalValue string `json:"externalValue,omitempty"`
}
Example represents an example value. The value field and externalValue field are mutually exclusive.
type Exampler ¶
type Exampler interface {
OpenAPIExample() any
}
Exampler can be implemented by types to provide an example value for the generated JSON Schema. The returned value is set as the "example" field on the component schema.
func (u User) OpenAPIExample() any {
return User{ID: "550e8400-e29b-41d4-a716-446655440000", Name: "Alice"}
}
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-9.5
type ExternalDocs ¶
type ExternalDocs struct {
Description string `json:"description,omitempty"`
URL string `json:"url"`
}
ExternalDocs allows referencing external documentation.
See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object
type HandleConfig ¶
type HandleConfig struct {
// UI selects the interactive docs UI (default: DocsSwaggerUI).
UI DocsUI
// Title overrides the HTML page title (default: spec info.title).
Title string
// JSONFilename is the path for the JSON spec endpoint
// (default: "schema.json"). Set to "-" to disable.
//
// Relative paths are joined with the base path:
//
// "schema.json" -> <basePath>/schema.json
// "data/openapi.json" -> <basePath>/data/openapi.json
//
// Absolute paths (starting with "/") are used as-is:
//
// "/api/v1/swagger.json" -> /api/v1/swagger.json
JSONFilename string
// YAMLFilename is the path for the YAML spec endpoint
// (default: "schema.yaml"). Set to "-" to disable.
// Follows the same absolute/relative rules as JSONFilename.
YAMLFilename string
// DisableDocs disables the interactive HTML docs UI endpoint.
DisableDocs bool
// SwaggerUIConfig provides additional SwaggerUIBundle configuration options.
// These are rendered as JavaScript object properties alongside the url and
// dom_id defaults. For example, {"docExpansion": "none"} produces:
//
// SwaggerUIBundle({url: "...", dom_id: "#swagger-ui", "docExpansion": "none"});
//
// Only used when UI is DocsSwaggerUI (the default).
//
// See: https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
SwaggerUIConfig map[string]any
}
HandleConfig configures the endpoints registered by Handle. JSON and YAML endpoints serve the serialized OpenAPI Document.
type Header ¶
type Header struct {
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
AllowReserved bool `json:"allowReserved,omitempty"`
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
Examples map[string]*Example `json:"examples,omitempty"`
Content map[string]*MediaType `json:"content,omitempty"`
}
Header describes a single header. Header Object follows the same structure as Parameter Object with the following differences: name is specified in the key of the containing map and "in" is implicitly "header".
type Info ¶
type Info struct {
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Contact *Contact `json:"contact,omitempty"`
License *License `json:"license,omitempty"`
Version string `json:"version"`
}
Info provides metadata about the API.
type License ¶
type License struct {
Name string `json:"name"`
Identifier string `json:"identifier,omitempty"`
URL string `json:"url,omitempty"`
}
License represents license information for the API.
type Link ¶
type Link struct {
OperationRef string `json:"operationRef,omitempty"`
OperationID string `json:"operationId,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
RequestBody any `json:"requestBody,omitempty"`
Description string `json:"description,omitempty"`
Server *Server `json:"server,omitempty"`
}
Link represents a possible design-time link for a response. Links provide a known relationship and traversal mechanism between responses and other operations.
type MediaType ¶
type MediaType struct {
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
Examples map[string]*Example `json:"examples,omitempty"`
Encoding map[string]*Encoding `json:"encoding,omitempty"`
}
MediaType describes a media type with a schema and optional example. Each Media Type Object is keyed by its MIME type (e.g., "application/json") inside a content map.
type Namer ¶ added in v0.3.0
type Namer interface {
OpenAPIName() string
}
Namer can be implemented by types to override the default component schema name. The returned string is used as the base name in the Components Object schemas map. Standard collision-resolution logic (package prefix, numeric suffix) still applies when names collide.
func (User) OpenAPIName() string {
return "UserAccount"
}
See: https://spec.openapis.org/oas/v3.1.0#components-object (schemas)
type OAuthFlow ¶
type OAuthFlow struct {
AuthorizationURL string `json:"authorizationUrl,omitempty"`
TokenURL string `json:"tokenUrl,omitempty"`
RefreshURL string `json:"refreshUrl,omitempty"`
Scopes map[string]string `json:"scopes"`
}
OAuthFlow describes a single OAuth2 flow configuration.
type OAuthFlows ¶
type OAuthFlows struct {
Implicit *OAuthFlow `json:"implicit,omitempty"`
Password *OAuthFlow `json:"password,omitempty"`
ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}
OAuthFlows describes the available OAuth2 flows.
See: https://spec.openapis.org/oas/v3.1.0#oauth-flows-object
type Operation ¶
type Operation struct {
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
OperationID string `json:"operationId,omitempty"`
Parameters []*Parameter `json:"parameters,omitempty"`
RequestBody *RequestBody `json:"requestBody,omitempty"`
Responses map[string]*Response `json:"responses,omitempty"`
Callbacks map[string]*Callback `json:"callbacks,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
Security []SecurityRequirement `json:"security,omitempty"`
Servers []Server `json:"servers,omitempty"`
}
Operation describes a single API operation on a path.
type OperationBuilder ¶
type OperationBuilder struct {
// contains filtered or unexported fields
}
OperationBuilder provides a fluent API for attaching OpenAPI metadata to a named route. It assembles an Operation Object.
See: https://spec.openapis.org/oas/v3.1.0#operation-object
func (*OperationBuilder) Callback ¶
func (b *OperationBuilder) Callback(name string, cb *Callback) *OperationBuilder
Callback adds a callback to the operation.
func (*OperationBuilder) DefaultResponse ¶
func (b *OperationBuilder) DefaultResponse(body any) *OperationBuilder
DefaultResponse registers an application/json response for the "default" status key. The default response catches any status code not covered by specific responses. Pass nil body for a default response with no content.
See: https://spec.openapis.org/oas/v3.1.0#responses-object (default)
func (*OperationBuilder) DefaultResponseContent ¶
func (b *OperationBuilder) DefaultResponseContent(contentType string, body any) *OperationBuilder
DefaultResponseContent registers a response with the given content type for the "default" status key.
See: https://spec.openapis.org/oas/v3.1.0#responses-object (default) See: https://spec.openapis.org/oas/v3.1.0#media-type-object
func (*OperationBuilder) DefaultResponseDescription ¶
func (b *OperationBuilder) DefaultResponseDescription(desc string) *OperationBuilder
DefaultResponseDescription overrides the auto-generated description for the default response.
See: https://spec.openapis.org/oas/v3.1.0#response-object (description)
func (*OperationBuilder) DefaultResponseHeader ¶
func (b *OperationBuilder) DefaultResponseHeader(name string, h *Header) *OperationBuilder
DefaultResponseHeader adds a header to the default response.
See: https://spec.openapis.org/oas/v3.1.0#response-object (headers) See: https://spec.openapis.org/oas/v3.1.0#header-object
func (*OperationBuilder) DefaultResponseLink ¶
func (b *OperationBuilder) DefaultResponseLink(name string, l *Link) *OperationBuilder
DefaultResponseLink adds a link to the default response.
See: https://spec.openapis.org/oas/v3.1.0#response-object (links) See: https://spec.openapis.org/oas/v3.1.0#link-object
func (*OperationBuilder) Deprecated ¶
func (b *OperationBuilder) Deprecated() *OperationBuilder
Deprecated marks the operation as deprecated.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (deprecated)
func (*OperationBuilder) Description ¶
func (b *OperationBuilder) Description(d string) *OperationBuilder
Description sets the operation description.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (description)
func (*OperationBuilder) ExternalDocs ¶
func (b *OperationBuilder) ExternalDocs(url, description string) *OperationBuilder
ExternalDocs sets external documentation for the operation.
See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object
func (*OperationBuilder) OperationID ¶
func (b *OperationBuilder) OperationID(id string) *OperationBuilder
OperationID sets a custom operation ID, overriding the auto-detected route name. This is useful with Route() where the mux route may not have a name.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (operationId)
func (*OperationBuilder) Parameter ¶
func (b *OperationBuilder) Parameter(param *Parameter) *OperationBuilder
Parameter adds a custom parameter to the operation.
func (*OperationBuilder) Request ¶
func (b *OperationBuilder) Request(body any) *OperationBuilder
Request registers an application/json request body type for the operation. This is a shortcut for RequestContent("application/json", body).
See: https://spec.openapis.org/oas/v3.1.0#request-body-object
func (*OperationBuilder) RequestContent ¶
func (b *OperationBuilder) RequestContent(contentType string, body any) *OperationBuilder
RequestContent registers a request body with the given content type. The body can be a Go type (schema generated via reflection), a *Schema for explicit schema control, or nil for a content type with no schema.
See: https://spec.openapis.org/oas/v3.1.0#request-body-object
func (*OperationBuilder) RequestDescription ¶
func (b *OperationBuilder) RequestDescription(desc string) *OperationBuilder
RequestDescription sets the description for the request body.
See: https://spec.openapis.org/oas/v3.1.0#request-body-object (description)
func (*OperationBuilder) RequestRequired ¶
func (b *OperationBuilder) RequestRequired(required bool) *OperationBuilder
RequestRequired sets whether the request body is required. By default, request bodies are required (true).
See: https://spec.openapis.org/oas/v3.1.0#request-body-object (required)
func (*OperationBuilder) Response ¶
func (b *OperationBuilder) Response(statusCode int, body any) *OperationBuilder
Response registers an application/json response type for the given HTTP status code. Pass nil body for responses with no content (e.g., 204). This is a shortcut for ResponseContent(statusCode, "application/json", body) when body is non-nil.
See: https://spec.openapis.org/oas/v3.1.0#responses-object See: https://spec.openapis.org/oas/v3.1.0#response-object
func (*OperationBuilder) ResponseContent ¶
func (b *OperationBuilder) ResponseContent(statusCode int, contentType string, body any) *OperationBuilder
ResponseContent registers a response with the given status code and content type. The body can be a Go type (schema generated via reflection), a *Schema for explicit schema control, or nil for a content type with no schema.
func (*OperationBuilder) ResponseDescription ¶
func (b *OperationBuilder) ResponseDescription(statusCode int, desc string) *OperationBuilder
ResponseDescription overrides the auto-generated description for a response. By default, descriptions are derived from HTTP status text (e.g., "OK", "Not Found").
See: https://spec.openapis.org/oas/v3.1.0#response-object (description)
func (*OperationBuilder) ResponseHeader ¶
func (b *OperationBuilder) ResponseHeader(statusCode int, name string, h *Header) *OperationBuilder
ResponseHeader adds a header to the response for the given HTTP status code.
See: https://spec.openapis.org/oas/v3.1.0#response-object (headers)
func (*OperationBuilder) ResponseLink ¶
func (b *OperationBuilder) ResponseLink(statusCode int, name string, l *Link) *OperationBuilder
ResponseLink adds a link to the response for the given HTTP status code.
See: https://spec.openapis.org/oas/v3.1.0#response-object (links) See: https://spec.openapis.org/oas/v3.1.0#link-object
func (*OperationBuilder) Security ¶
func (b *OperationBuilder) Security(reqs ...SecurityRequirement) *OperationBuilder
Security sets operation-level security requirements. Call with no arguments to explicitly mark the operation as unauthenticated (overrides document-level security).
See: https://spec.openapis.org/oas/v3.1.0#operation-object (security) See: https://spec.openapis.org/oas/v3.1.0#security-requirement-object
func (*OperationBuilder) Server ¶
func (b *OperationBuilder) Server(server Server) *OperationBuilder
Server adds a server override for the operation.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (servers)
func (*OperationBuilder) Summary ¶
func (b *OperationBuilder) Summary(s string) *OperationBuilder
Summary sets the operation summary.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (summary)
func (*OperationBuilder) Tags ¶
func (b *OperationBuilder) Tags(tags ...string) *OperationBuilder
Tags adds one or more tags to the operation.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (tags)
type Parameter ¶
type Parameter struct {
Name string `json:"name"`
In string `json:"in"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
Style string `json:"style,omitempty"`
Explode *bool `json:"explode,omitempty"`
AllowReserved bool `json:"allowReserved,omitempty"`
Schema *Schema `json:"schema,omitempty"`
Example any `json:"example,omitempty"`
Examples map[string]*Example `json:"examples,omitempty"`
Content map[string]*MediaType `json:"content,omitempty"`
}
Parameter describes a single operation parameter. The "in" field determines the parameter location: "query", "header", "path", or "cookie". Parameters with the same name and location must be unique within an operation.
type PathItem ¶
type PathItem struct {
Ref string `json:"$ref,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Get *Operation `json:"get,omitempty"`
Put *Operation `json:"put,omitempty"`
Post *Operation `json:"post,omitempty"`
Delete *Operation `json:"delete,omitempty"`
Options *Operation `json:"options,omitempty"`
Head *Operation `json:"head,omitempty"`
Patch *Operation `json:"patch,omitempty"`
Trace *Operation `json:"trace,omitempty"`
Servers []Server `json:"servers,omitempty"`
Parameters []*Parameter `json:"parameters,omitempty"`
}
PathItem describes the operations available on a single path.
type RequestBody ¶
type RequestBody struct {
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Content map[string]*MediaType `json:"content,omitempty"`
}
RequestBody describes a single request body.
See: https://spec.openapis.org/oas/v3.1.0#request-body-object
type Response ¶
type Response struct {
Description string `json:"description"`
Headers map[string]*Header `json:"headers,omitempty"`
Content map[string]*MediaType `json:"content,omitempty"`
Links map[string]*Link `json:"links,omitempty"`
}
Response describes a single response from an API operation. The description field is REQUIRED per the specification.
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup provides shared OpenAPI metadata defaults for a logical group of operations. It creates OperationBuilder instances pre-populated with the group defaults. Groups register builders into the parent Spec's existing maps so Build requires no changes.
See: https://spec.openapis.org/oas/v3.1.0#operation-object
func (*RouteGroup) DefaultResponse ¶
func (g *RouteGroup) DefaultResponse(body any) *RouteGroup
DefaultResponse adds a shared application/json default response (catch-all for status codes not covered by specific responses).
See: https://spec.openapis.org/oas/v3.1.0#responses-object (default)
func (*RouteGroup) DefaultResponseDescription ¶
func (g *RouteGroup) DefaultResponseDescription(desc string) *RouteGroup
DefaultResponseDescription sets a custom description for the shared default response.
See: https://spec.openapis.org/oas/v3.1.0#response-object (description)
func (*RouteGroup) DefaultResponseHeader ¶
func (g *RouteGroup) DefaultResponseHeader(name string, h *Header) *RouteGroup
DefaultResponseHeader adds a shared header to the default response.
See: https://spec.openapis.org/oas/v3.1.0#response-object (headers) See: https://spec.openapis.org/oas/v3.1.0#header-object
func (*RouteGroup) Deprecated ¶
func (g *RouteGroup) Deprecated() *RouteGroup
Deprecated marks all operations in this group as deprecated. This is a one-way latch: individual operations cannot undo group deprecation.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (deprecated)
func (*RouteGroup) ExternalDocs ¶
func (g *RouteGroup) ExternalDocs(url, description string) *RouteGroup
ExternalDocs sets external documentation for the group. Operations created through this group inherit this value unless they call ExternalDocs themselves, which replaces it.
See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object
func (*RouteGroup) Op ¶
func (g *RouteGroup) Op(routeName string) *OperationBuilder
Op returns an OperationBuilder for the named route, pre-populated with this group's defaults. If the route name was previously registered, the existing builder is returned (without applying group defaults again).
See: https://spec.openapis.org/oas/v3.1.0#operation-object (operationId)
func (*RouteGroup) Parameter ¶
func (g *RouteGroup) Parameter(param *Parameter) *RouteGroup
Parameter adds a common parameter to the group defaults. Operations created through this group inherit these parameters and may add more.
func (*RouteGroup) Response ¶
func (g *RouteGroup) Response(statusCode int, body any) *RouteGroup
Response adds a shared application/json response for the given HTTP status code. All operations created through this group inherit this response. An operation-level Response call for the same status code overrides the group default.
See: https://spec.openapis.org/oas/v3.1.0#responses-object See: https://spec.openapis.org/oas/v3.1.0#response-object
func (*RouteGroup) ResponseContent ¶
func (g *RouteGroup) ResponseContent(statusCode int, contentType string, body any) *RouteGroup
ResponseContent adds a shared response with the given status code and content type. Use this for non-JSON responses (e.g., "application/xml").
See: https://spec.openapis.org/oas/v3.1.0#response-object See: https://spec.openapis.org/oas/v3.1.0#media-type-object
func (*RouteGroup) ResponseDescription ¶
func (g *RouteGroup) ResponseDescription(statusCode int, desc string) *RouteGroup
ResponseDescription sets a custom description for a shared group response.
See: https://spec.openapis.org/oas/v3.1.0#response-object (description)
func (*RouteGroup) ResponseHeader ¶
func (g *RouteGroup) ResponseHeader(statusCode int, name string, h *Header) *RouteGroup
ResponseHeader adds a shared header to the response for the given HTTP status code. All operations in this group inherit this header.
See: https://spec.openapis.org/oas/v3.1.0#response-object (headers) See: https://spec.openapis.org/oas/v3.1.0#header-object
func (*RouteGroup) ResponseLink ¶
func (g *RouteGroup) ResponseLink(statusCode int, name string, l *Link) *RouteGroup
ResponseLink adds a shared link to the response for the given HTTP status code. All operations in this group inherit this link.
See: https://spec.openapis.org/oas/v3.1.0#response-object (links) See: https://spec.openapis.org/oas/v3.1.0#link-object
func (*RouteGroup) Route ¶
func (g *RouteGroup) Route(route *mux.Route) *OperationBuilder
Route attaches an OperationBuilder to an existing mux route, pre-populated with this group's defaults.
func (*RouteGroup) Security ¶
func (g *RouteGroup) Security(reqs ...SecurityRequirement) *RouteGroup
Security sets the group-level security requirements. Operations created through this group inherit these requirements unless they call Security themselves, which replaces the group value. Call with no arguments to mark the group as public (overrides document-level security).
See: https://spec.openapis.org/oas/v3.1.0#operation-object (security) See: https://spec.openapis.org/oas/v3.1.0#security-requirement-object
func (*RouteGroup) Server ¶
func (g *RouteGroup) Server(server Server) *RouteGroup
Server adds a server override to the group defaults.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (servers)
func (*RouteGroup) Tags ¶
func (g *RouteGroup) Tags(tags ...string) *RouteGroup
Tags appends tags to the group defaults. Operations created through this group will inherit these tags and may add more via their own Tags call.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (tags)
func (*RouteGroup) Webhook ¶
func (g *RouteGroup) Webhook(name, method string) *OperationBuilder
Webhook registers an OpenAPI webhook with the given name and HTTP method, pre-populated with this group's defaults.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object (webhooks)
type Schema ¶
type Schema struct {
// JSON Schema core identifiers (Draft 2020-12, section 8).
// See: https://json-schema.org/draft/2020-12/json-schema-core#section-8
ID string `json:"$id,omitempty"`
SchemaURI string `json:"$schema,omitempty"`
Ref string `json:"$ref,omitempty"`
DynamicAnchor string `json:"$dynamicAnchor,omitempty"`
Comment string `json:"$comment,omitempty"`
Defs map[string]*Schema `json:"$defs,omitempty"`
// Type and format.
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
// See: https://spec.openapis.org/oas/v3.1.0#data-types
Type SchemaType `json:"type,omitzero" yaml:"type,omitempty"`
Format string `json:"format,omitempty"`
// Metadata annotations.
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-9
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Default any `json:"default,omitempty"`
Example any `json:"example,omitempty"`
Examples []any `json:"examples,omitempty"`
Deprecated bool `json:"deprecated,omitempty"`
ReadOnly bool `json:"readOnly,omitempty"`
WriteOnly bool `json:"writeOnly,omitempty"`
// Numeric constraints.
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2
MultipleOf *float64 `json:"multipleOf,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
// String constraints.
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.3
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
// Array constraints.
// See: https://json-schema.org/draft/2020-12/json-schema-core#section-10.3.1
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.4
Items *Schema `json:"items,omitempty"`
PrefixItems []*Schema `json:"prefixItems,omitempty"`
Contains *Schema `json:"contains,omitempty"`
MinItems *int `json:"minItems,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
UniqueItems bool `json:"uniqueItems,omitempty"`
UnevaluatedItems *Schema `json:"unevaluatedItems,omitempty"`
// Object constraints.
// See: https://json-schema.org/draft/2020-12/json-schema-core#section-10.3.2
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.5
Properties map[string]*Schema `json:"properties,omitempty"`
PatternProperties map[string]*Schema `json:"patternProperties,omitempty"`
AdditionalProperties *Schema `json:"additionalProperties,omitempty"`
UnevaluatedProperties *Schema `json:"unevaluatedProperties,omitempty"`
PropertyNames *Schema `json:"propertyNames,omitempty"`
Required []string `json:"required,omitempty"`
MinProperties *int `json:"minProperties,omitempty"`
MaxProperties *int `json:"maxProperties,omitempty"`
DependentRequired map[string][]string `json:"dependentRequired,omitempty"`
DependentSchemas map[string]*Schema `json:"dependentSchemas,omitempty"`
// Enum and const.
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.2
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.3
Enum []any `json:"enum,omitempty"`
Const any `json:"const,omitzero"`
// Composition keywords.
// See: https://json-schema.org/draft/2020-12/json-schema-core#section-10.2.1
AllOf []*Schema `json:"allOf,omitempty"`
OneOf []*Schema `json:"oneOf,omitempty"`
AnyOf []*Schema `json:"anyOf,omitempty"`
Not *Schema `json:"not,omitempty"`
// Conditional subschemas.
// See: https://json-schema.org/draft/2020-12/json-schema-core#section-10.2.2
If *Schema `json:"if,omitempty"`
Then *Schema `json:"then,omitempty"`
Else *Schema `json:"else,omitempty"`
// Content encoding.
// See: https://json-schema.org/draft/2020-12/json-schema-validation#section-8
ContentEncoding string `json:"contentEncoding,omitempty"`
ContentMediaType string `json:"contentMediaType,omitempty"`
ContentSchema *Schema `json:"contentSchema,omitempty"`
// OpenAPI-specific extensions to JSON Schema.
// See: https://spec.openapis.org/oas/v3.1.0#fixed-fields-20
Discriminator *Discriminator `json:"discriminator,omitempty"`
ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
XML *XML `json:"xml,omitempty"`
}
Schema represents a JSON Schema object used in OpenAPI v3.1.0. OpenAPI 3.1.0 aligns fully with JSON Schema Draft 2020-12 and adds a few OpenAPI-specific keywords (discriminator, externalDocs, xml).
See: https://spec.openapis.org/oas/v3.1.0#schema-object See: https://json-schema.org/draft/2020-12/json-schema-core See: https://json-schema.org/draft/2020-12/json-schema-validation
type SchemaGenerator ¶
type SchemaGenerator struct {
// contains filtered or unexported fields
}
SchemaGenerator converts Go types to JSON Schema objects and collects named types into a component schemas map for $ref deduplication.
See: https://spec.openapis.org/oas/v3.1.0#schema-object See: https://spec.openapis.org/oas/v3.1.0#components-object (schemas)
func NewSchemaGenerator ¶
func NewSchemaGenerator() *SchemaGenerator
NewSchemaGenerator creates a new schema generator.
See: https://spec.openapis.org/oas/v3.1.0#schema-object See: https://spec.openapis.org/oas/v3.1.0#components-object (schemas)
func (*SchemaGenerator) Document ¶ added in v0.3.0
func (g *SchemaGenerator) Document(info Info) *Document
Document builds a complete OpenAPI Document from the collected component schemas. This allows exporting a spec without a mux router, useful for non-server applications such as schema-only documentation or code generation tooling.
The returned document has its own schemas map (adding more schemas to the generator will not affect previously returned documents), but the individual *Schema values are shared with the generator. Callers should not mutate the schema objects in the returned document.
gen := openapi.NewSchemaGenerator()
gen.Generate(User{})
gen.Generate(Order{})
doc := gen.Document(openapi.Info{Title: "My API", Version: "1.0.0"})
data, _ := doc.JSON()
func (*SchemaGenerator) Generate ¶
func (g *SchemaGenerator) Generate(v any) *Schema
Generate produces a JSON Schema for the given Go value. Named struct types are stored in the generator's component schemas and referenced via $ref.
See: https://spec.openapis.org/oas/v3.1.0#schema-object See: https://json-schema.org/draft/2020-12/json-schema-core#section-8.2.3 ($ref)
func (*SchemaGenerator) Schemas ¶
func (g *SchemaGenerator) Schemas() map[string]*Schema
Schemas returns the collected component schemas.
See: https://spec.openapis.org/oas/v3.1.0#components-object (schemas)
type SchemaType ¶
type SchemaType struct {
// contains filtered or unexported fields
}
SchemaType represents a JSON Schema type that can be a single string or an array of strings (per JSON Schema Draft 2020-12, section 6.1.1).
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func TypeArray ¶
func TypeArray(types ...string) SchemaType
TypeArray creates a SchemaType with multiple types (e.g., ["string", "null"]). Used for nullable types per JSON Schema Draft 2020-12.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func TypeString ¶
func TypeString(t string) SchemaType
TypeString creates a SchemaType with a single type.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (SchemaType) IsEmpty ¶
func (st SchemaType) IsEmpty() bool
IsEmpty reports whether the schema type is unset.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (SchemaType) IsZero ¶
func (st SchemaType) IsZero() bool
IsZero implements the yaml.v3 IsZeroer interface so that omitempty on YAML struct tags correctly omits an unset type field.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (SchemaType) MarshalJSON ¶
func (st SchemaType) MarshalJSON() ([]byte, error)
MarshalJSON encodes the schema type as a JSON string (single type) or JSON array (multiple types).
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (SchemaType) MarshalYAML ¶
func (st SchemaType) MarshalYAML() (any, error)
MarshalYAML encodes the schema type as a YAML scalar (single type) or YAML sequence (multiple types).
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (*SchemaType) UnmarshalJSON ¶
func (st *SchemaType) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the schema type from either a JSON string or array.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (*SchemaType) UnmarshalYAML ¶
func (st *SchemaType) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML decodes the schema type from either a YAML scalar or sequence.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
func (SchemaType) Values ¶
func (st SchemaType) Values() []string
Values returns the underlying type values.
See: https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1
type SecurityRequirement ¶
SecurityRequirement lists required security schemes for an operation. Each key maps to a list of scope names required for execution (can be empty for schemes not using scopes, such as HTTP basic auth).
See: https://spec.openapis.org/oas/v3.1.0#security-requirement-object
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Flows *OAuthFlows `json:"flows,omitempty"`
OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"`
}
SecurityScheme defines a security scheme used by API operations. The "type" field determines the scheme: "apiKey", "http", "mutualTLS", "oauth2", or "openIdConnect".
See: https://spec.openapis.org/oas/v3.1.0#security-scheme-object
type Server ¶
type Server struct {
URL string `json:"url"`
Description string `json:"description,omitempty"`
Variables map[string]*ServerVariable `json:"variables,omitempty"`
}
Server represents a server.
type ServerVariable ¶
type ServerVariable struct {
Enum []string `json:"enum,omitempty"`
Default string `json:"default"`
Description string `json:"description,omitempty"`
}
ServerVariable represents a server variable for URL template substitution.
See: https://spec.openapis.org/oas/v3.1.0#server-variable-object
type Spec ¶
type Spec struct {
// contains filtered or unexported fields
}
Spec collects OpenAPI metadata for routes and builds a complete Document.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object
func (*Spec) AddComponentCallback ¶
AddComponentCallback registers a reusable callback in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (callbacks)
func (*Spec) AddComponentExample ¶
AddComponentExample registers a reusable example in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (examples)
func (*Spec) AddComponentHeader ¶
AddComponentHeader registers a reusable header in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (headers)
func (*Spec) AddComponentLink ¶
AddComponentLink registers a reusable link in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (links)
func (*Spec) AddComponentParameter ¶
AddComponentParameter registers a reusable parameter in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (parameters)
func (*Spec) AddComponentPathItem ¶
AddComponentPathItem registers a reusable path item in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (pathItems)
func (*Spec) AddComponentRequestBody ¶
func (s *Spec) AddComponentRequestBody(name string, rb *RequestBody) *Spec
AddComponentRequestBody registers a reusable request body in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (requestBodies)
func (*Spec) AddComponentResponse ¶
AddComponentResponse registers a reusable response in components.
See: https://spec.openapis.org/oas/v3.1.0#components-object (responses)
func (*Spec) AddPathParameter ¶
AddPathParameter adds a shared parameter for a specific path. The path must use OpenAPI format (e.g., "/users/{id}"). Path-level parameters apply to all operations under this path and can be overridden at the operation level.
See: https://spec.openapis.org/oas/v3.1.0#path-item-object (parameters)
func (*Spec) AddPathServer ¶
AddPathServer adds a server override for a specific path. The path must use OpenAPI format (e.g., "/files", "/users/{id}"). All operations under this path inherit these servers, overriding the document-level servers.
See: https://spec.openapis.org/oas/v3.1.0#path-item-object (servers)
func (*Spec) AddSecurityScheme ¶
func (s *Spec) AddSecurityScheme(name string, scheme *SecurityScheme) *Spec
AddSecurityScheme registers a reusable security scheme in components.
See: https://spec.openapis.org/oas/v3.1.0#security-scheme-object
func (*Spec) AddServer ¶
AddServer adds a server to the spec.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object (servers)
func (*Spec) Group ¶
func (s *Spec) Group() *RouteGroup
Group creates a new RouteGroup for applying shared OpenAPI metadata defaults to a logical group of operations. The returned group provides the same Route and Op methods as Spec, but pre-populates each OperationBuilder with the group's default tags, security, servers, parameters, and external docs.
func (*Spec) Handle ¶
func (s *Spec) Handle(r *mux.Router, basePath string, cfg *HandleConfig)
Handle registers OpenAPI endpoints under the given base path on the router. The base path is normalized (trailing slash stripped). Depending on config, the following routes are registered:
<basePath>/ - interactive HTML docs (unless DisableDocs) <JSONFilename path> - OpenAPI spec as JSON (unless JSONFilename is "-") <YAMLFilename path> - OpenAPI spec as YAML (unless YAMLFilename is "-")
The config parameter is optional; pass nil for defaults:
spec.Handle(r, "/swagger", nil)
Filenames are relative to basePath by default. Use an absolute path (starting with "/") to serve the schema at an independent location:
spec.Handle(r, "/swagger", &HandleConfig{
JSONFilename: "/api/v1/swagger.json",
YAMLFilename: "-",
})
// /swagger/ -> docs UI pointing to /api/v1/swagger.json
// /api/v1/swagger.json -> JSON spec
Both <basePath> and <basePath>/ serve the docs UI. The spec is built once on first request and cached.
func (*Spec) Op ¶
func (s *Spec) Op(routeName string) *OperationBuilder
Op returns an OperationBuilder for the named route. If the route name was not previously registered, a new builder is created.
See: https://spec.openapis.org/oas/v3.1.0#operation-object (operationId)
func (*Spec) Route ¶
func (s *Spec) Route(route *mux.Route) *OperationBuilder
Route attaches an OperationBuilder to an existing mux route. The route can be configured with any mux features (Methods, Headers, Queries, etc.).
func (*Spec) SetExternalDocs ¶
SetExternalDocs sets the document-level external documentation link.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object (externalDocs) See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object
func (*Spec) SetPathDescription ¶
SetPathDescription sets a detailed description for a specific path. The path must use OpenAPI format (e.g., "/users/{id}"). The description applies to all operations under this path and supports Markdown.
See: https://spec.openapis.org/oas/v3.1.0#path-item-object (description)
func (*Spec) SetPathSummary ¶
SetPathSummary sets a brief summary for a specific path. The path must use OpenAPI format (e.g., "/users/{id}"). The summary applies to all operations under this path.
See: https://spec.openapis.org/oas/v3.1.0#path-item-object (summary)
func (*Spec) SetSecurity ¶
func (s *Spec) SetSecurity(reqs ...SecurityRequirement) *Spec
SetSecurity sets the document-level security requirements.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object (security) See: https://spec.openapis.org/oas/v3.1.0#security-requirement-object
func (*Spec) Webhook ¶
func (s *Spec) Webhook(name, method string) *OperationBuilder
Webhook registers an OpenAPI webhook with the given name and HTTP method. Webhooks describe API-initiated callbacks that are not tied to a specific path on the mux router. The returned OperationBuilder has the same fluent API as Route and Op.
See: https://spec.openapis.org/oas/v3.1.0#openapi-object (webhooks)
type Tag ¶
type Tag struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
}
Tag adds metadata to a single tag used by Operation Objects.
type XML ¶
type XML struct {
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
Prefix string `json:"prefix,omitempty"`
Attribute bool `json:"attribute,omitempty"`
Wrapped bool `json:"wrapped,omitempty"`
}
XML describes XML-specific metadata for properties, used when producing XML output.