openapi

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 17 Imported by: 0

README

openapi

Automatic OpenAPI v3.1.0 specification generation from mux router routes.

Converts Go types to JSON Schema (Draft 2020-12) via reflection and openapi struct tags. Named struct types are deduplicated into #/components/schemas with $ref references. Path parameter macros ({id:uuid}, {page:int}, etc.) are mapped to OpenAPI types automatically.

Getting started

Create a spec, define routes on the mux router, and attach OpenAPI metadata.

r := mux.NewRouter()
spec := openapi.NewSpec(openapi.Info{Title: "My API", Version: "1.0.0"})
Attaching metadata with Route

Route takes a *mux.Route directly. Full mux flexibility is preserved -- use any mux.Route configuration (Methods, Headers, Queries, Schemes, etc.).

spec.Route(r.HandleFunc("/users", listUsers).Methods(http.MethodGet)).
    Summary("List all users").
    Tags("users").
    Response(http.StatusOK, []User{})

spec.Route(r.HandleFunc("/users", createUser).Methods(http.MethodPost)).
    Summary("Create a user").
    Tags("users").
    Request(CreateUserRequest{}).
    Response(http.StatusCreated, User{}).
    Response(http.StatusBadRequest, ErrorResponse{})
Attaching metadata with Op (named routes)

Op matches metadata to routes by name. Define routes first with .Name(), then attach metadata separately.

r.HandleFunc("/users", listUsers).Methods(http.MethodGet).Name("listUsers")
r.HandleFunc("/users/{id:uuid}", getUser).Methods(http.MethodGet).Name("getUser")

spec.Op("listUsers").
    Summary("List all users").
    Tags("users").
    Response(http.StatusOK, []User{})

spec.Op("getUser").
    Summary("Get user by ID").
    Tags("users").
    Response(http.StatusOK, User{})

Both Route and Op return an *OperationBuilder with the same fluent API.

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.

users := spec.Group().
    Tags("users").
    Security(openapi.SecurityRequirement{"bearerAuth": {}}).
    Response(http.StatusForbidden, ErrorResponse{}).
    ResponseDescription(http.StatusForbidden, "Insufficient permissions").
    Response(http.StatusNotFound, ErrorResponse{})

users.Route(r.HandleFunc("/users", listUsers).Methods(http.MethodGet)).
    Summary("List users").
    Response(http.StatusOK, []User{})
    // inherits 403 and 404 from group

users.Route(r.HandleFunc("/users/{id}", getUser).Methods(http.MethodGet)).
    Summary("Get user").
    Response(http.StatusOK, User{})
    // inherits 403 and 404 from group

Groups support Tags, Security, Deprecated, Server, Parameter, ExternalDocs, and the full response API: Response, ResponseContent, ResponseDescription, ResponseHeader, ResponseLink, DefaultResponse, DefaultResponseDescription, DefaultResponseHeader. Both Route and Op are available on a group.

An operation-level Response call for the same status code overrides the group default for that code.

Override/merge semantics per field:

Field Behavior Description
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

Request and response bodies

JSON (default)

Request and Response are JSON shortcuts. Pass a Go type for automatic schema generation via reflection.

spec.Op("create").
    Request(CreateUserRequest{}).
    Response(http.StatusCreated, User{}).
    Response(http.StatusBadRequest, ErrorResponse{})

Pass nil body to Response for status codes with no content:

spec.Op("delete").Response(http.StatusNoContent, nil)
Custom content types

Use RequestContent and ResponseContent for any content type:

// 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{})

// Plain text
spec.Op("text").ResponseContent(http.StatusOK, "text/plain", &openapi.Schema{
    Type: openapi.TypeString("string"),
})

// Vendor-specific type
spec.Op("create").RequestContent("application/vnd.mycompany.v2+json", Employee{})

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.

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"},
    })

DefaultResponseHeader and DefaultResponseLink target the default response:

spec.Op("getUser").
    Response(http.StatusOK, User{}).
    DefaultResponse(ErrorResponse{}).
    DefaultResponseHeader("X-Request-ID", &openapi.Header{
        Schema: &openapi.Schema{Type: openapi.TypeString("string")},
    }).
    DefaultResponseLink("GetError", &openapi.Link{OperationID: "getErrorDetails"})
Response descriptions

Response descriptions are auto-generated from HTTP status text (e.g., "OK", "Not Found"). Override them per status code:

spec.Op("getUser").
    Response(http.StatusOK, User{}).
    ResponseDescription(http.StatusOK, "The requested user").
    DefaultResponse(ErrorResponse{}).
    DefaultResponseDescription("Unexpected error")

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(http.StatusOK, []User{})

Parameters

Path parameters

Path parameters from mux route macros are generated automatically with correct OpenAPI types. No manual parameter registration is needed.

// {id:uuid} -> type: string, format: uuid
spec.Route(r.HandleFunc("/users/{id:uuid}", getUser).Methods(http.MethodGet))

Add custom parameters at the operation level:

spec.Op("listUsers").
    Parameter(&openapi.Parameter{
        Name: "page", In: "query",
        Schema: &openapi.Schema{Type: openapi.TypeString("integer")},
    }).
    Parameter(&openapi.Parameter{
        Name: "X-Request-ID", In: "header",
        Schema: &openapi.Schema{Type: openapi.TypeString("string")},
    })
Path-level parameters

Parameters shared across all operations under a path:

spec.AddPathParameter("/users/{id}", &openapi.Parameter{
    Name: "X-Tenant-ID", In: "header",
    Schema: &openapi.Schema{Type: openapi.TypeString("string")},
})

Security

Register security schemes and apply them at the document or operation level:

spec.AddSecurityScheme("bearerAuth", &openapi.SecurityScheme{
    Type:         "http",
    Scheme:       "bearer",
    BearerFormat: "JWT",
})
spec.SetSecurity(openapi.SecurityRequirement{"bearerAuth": {}})

Override security per operation. Call Security() with no arguments to mark an endpoint as public:

spec.Route(r.HandleFunc("/health", healthHandler).Methods(http.MethodGet)).
    Summary("Health check").
    Security()

Servers

Servers can be set at three levels: document, path, and operation. Lower levels override higher levels.

// Document-level (all operations inherit by default).
spec.AddServer(openapi.Server{URL: "https://api.example.com", Description: "Main"})

// 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"},
        },
    },
})

Tags

Tags used in operations are auto-collected and sorted alphabetically. Use AddTag to provide descriptions and external documentation:

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.

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")

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")},
})

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"})
spec.AddComponentCallback("onEvent", &cb)
spec.AddComponentPathItem("shared", &openapi.PathItem{})

Callbacks

Operations support callbacks:

cb := openapi.Callback{"{$request.body#/callbackUrl}": &openapi.PathItem{}}
spec.Op("subscribe").Callback("onEvent", &cb)

Webhooks

Webhooks describe API-initiated callbacks that are not tied to a specific path on the mux router. They appear in the webhooks section of the OpenAPI document.

spec.Webhook("newUser", http.MethodPost).
    Summary("New user notification").
    Tags("webhooks").
    Request(UserEvent{}).
    Response(http.StatusOK, nil)

Webhooks support the same fluent API as Route and Op. Group defaults also apply to webhooks:

events := spec.Group().
    Tags("events").
    Security(openapi.SecurityRequirement{"bearerAuth": {}})

events.Webhook("userCreated", http.MethodPost).
    Summary("User created event").
    Request(UserEvent{})

Struct tags

Use the openapi struct tag for schema enrichment:

type CreateUserInput struct {
    Name  string `json:"name" openapi:"description=User name,example=John,minLength=1,maxLength=100"`
    Email string `json:"email" openapi:"description=Email address,format=email"`
    Age   int    `json:"age,omitempty" openapi:"minimum=0,maximum=150"`
    Role  string `json:"role" openapi:"enum=admin|user|guest,description=User role"`
}

Supported keys:

Key Type Description
description string Field description
example any Example value (type-aware parsing)
format string JSON Schema format (email, uuid, date-time, etc.)
title string Schema title
minimum float64 Minimum value
maximum float64 Maximum value
exclusiveMinimum float64 Exclusive minimum
exclusiveMaximum float64 Exclusive maximum
multipleOf float64 Value must be a multiple of this
minLength int Minimum string length
maxLength int Maximum string length
pattern string Regex pattern
minItems int Minimum array items
maxItems int Maximum array items
uniqueItems bool Array items must be unique
minProperties int Minimum object properties
maxProperties int Maximum object properties
const any Fixed constant value
enum string Pipe-separated enum values
deprecated bool Mark as deprecated
readOnly bool Read-only field
writeOnly bool Write-only field

Type-level examples

Implement openapi.Exampler to provide a complete example for a type's component schema:

type User struct {
    ID    string `json:"id" openapi:"format=uuid"`
    Name  string `json:"name"`
    Email string `json:"email" openapi:"format=email"`
}

func (User) OpenAPIExample() any {
    return User{
        ID:    "550e8400-e29b-41d4-a716-446655440000",
        Name:  "Alice Smith",
        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.

Custom schema names

Implement openapi.Namer to override the default component schema name for a type:

type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

func (User) OpenAPIName() string {
    return "UserAccount"
}

The returned string is used as the base name in #/components/schemas. Standard collision resolution (package prefix, numeric suffix) still applies. If OpenAPIName returns an empty string, the default Go type name is used.

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   []ErrorDetail `json:"errors,omitempty"`
    Messages []string      `json:"messages,omitempty"`
    Result   T             `json:"result"`
}

// Single user → schema "ResponseDataUser"
spec.Op("getUser").Response(http.StatusOK, ResponseData[User]{})

// User list → schema "ResponseDataUserList"
spec.Op("listUsers").Response(http.StatusOK, ResponseData[[]User]{})

Schema name mapping:

Go type Component schema name
ResponseData[User] ResponseDataUser
ResponseData[[]User] ResponseDataUserList
ResponseData[pkg.Item] ResponseDataItem

Path parameter macros

Macro OpenAPI type format
uuid string uuid
int integer -
float number -
date string date
domain string hostname
slug string -
alpha string -
alphanum string -
hex string -

Type mapping

Go type JSON Schema
bool {type: "boolean"}
int, int8..int64, uint..uint64 {type: "integer"}
float32, float64 {type: "number"}
string {type: "string"}
[]byte {type: "string", format: "byte"}
time.Time {type: "string", format: "date-time"}
*T nullable via type array ["<type>", "null"]
[]T {type: "array", items: schema(T)}
map[string]V {type: "object", additionalProperties: schema(V)}
struct {type: "object", properties: {...}, required: [...]}

Serving

Handle registers all endpoints under a single base path. The config parameter is optional -- pass nil for defaults:

// Swagger UI (default) at /swagger/, schema at /swagger/schema.json and /swagger/schema.yaml
spec.Handle(r, "/swagger", nil)

// RapiDoc
spec.Handle(r, "/swagger", &openapi.HandleConfig{UI: openapi.DocsRapiDoc})

// Redoc
spec.Handle(r, "/swagger", &openapi.HandleConfig{UI: openapi.DocsRedoc})

// Custom filenames (relative to base path)
spec.Handle(r, "/swagger", &openapi.HandleConfig{JSONFilename: "openapi.json", YAMLFilename: "openapi.yaml"})

// Disable YAML endpoint
spec.Handle(r, "/swagger", &openapi.HandleConfig{YAMLFilename: "-"})

// Disable interactive docs, serve only spec files
spec.Handle(r, "/swagger", &openapi.HandleConfig{DisableDocs: true})
Swagger UI configuration

Pass additional SwaggerUIBundle options via SwaggerUIConfig. Values are JSON-encoded and rendered as JavaScript object properties:

spec.Handle(r, "/swagger", &openapi.HandleConfig{
    SwaggerUIConfig: map[string]any{
        "docExpansion":             "none",
        "deepLinking":              true,
        "defaultModelsExpandDepth": 0,
    },
})

This produces:

SwaggerUIBundle({url: "...", dom_id: "#swagger-ui", deepLinking: true, defaultModelsExpandDepth: 0, docExpansion: "none"});

Keys are sorted alphabetically for deterministic output. SwaggerUIConfig is only used when UI is DocsSwaggerUI (the default). See Swagger UI Configuration for available options.

Filename path resolution

Filenames are relative to the base path by default. Use an absolute path (starting with /) to serve the schema at an independent location:

// Relative (default): schema at /swagger/schema.json
spec.Handle(r, "/swagger", nil)

// Relative custom name: schema at /swagger/swagger.json
spec.Handle(r, "/swagger", &openapi.HandleConfig{JSONFilename: "swagger.json"})

// Relative nested path: schema at /swagger/data/openapi.json
spec.Handle(r, "/swagger", &openapi.HandleConfig{JSONFilename: "data/openapi.json"})

// Absolute path: docs at /swagger/, schema at /api/v1/swagger.json
spec.Handle(r, "/swagger", &openapi.HandleConfig{
    JSONFilename: "/api/v1/swagger.json",
    YAMLFilename: "-",
})

Path resolution examples with base path /swagger:

JSONFilename Resolved path
"schema.json" (default) /swagger/schema.json
"swagger.json" /swagger/swagger.json
"data/openapi.json" /swagger/data/openapi.json
"/api/v1/swagger.json" /api/v1/swagger.json

The same rules apply to YAMLFilename. JSON and YAML can use different path styles independently.

Both <basePath> and <basePath>/ serve the docs UI. The docs UI automatically references the correct schema path. All handlers build the document once on first request and cache the result.

Building the document

Build walks the mux router and assembles a complete *Document. This is called automatically by Handle, but can be used directly for custom serialization or testing:

doc := spec.Build(r)
jsonBytes, _ := doc.JSON()
yamlBytes, _ := doc.YAML()

Build resolves all registered routes (via Route and Op), generates JSON schemas for Go types, collects tags, and assembles components. Routes without OpenAPI metadata are skipped.

Exporting to JSON or YAML

Any *Document can be serialized to bytes using JSON() (indented) or YAML():

doc := spec.Build(r)
jsonBytes, _ := doc.JSON()
yamlBytes, _ := doc.YAML()

os.WriteFile("openapi.json", jsonBytes, 0644)
os.WriteFile("openapi.yaml", yamlBytes, 0644)

This works for all document sources: Build, SchemaGenerator.Document, DocumentFromJSON, DocumentFromYAML, and MergeDocuments.

Subrouter integration

The openapi package works with mux subrouters. Build walks the entire router tree, so routes registered on subrouters appear with their full paths:

r := mux.NewRouter()
api := r.PathPrefix("/api/v1").Subrouter()

spec := openapi.NewSpec(openapi.Info{Title: "My API", Version: "1.0.0"})

users := spec.Group().Tags("users")

users.Route(api.HandleFunc("/users", listUsers).Methods(http.MethodGet)).
    Summary("List users").
    Response(http.StatusOK, []User{})

users.Route(api.HandleFunc("/users/{id:uuid}", getUser).Methods(http.MethodGet)).
    Summary("Get user").
    Response(http.StatusOK, User{})

// Build walks the root router -- subrouter routes appear as /api/v1/users, /api/v1/users/{id}
doc := spec.Build(r)

Pass the root router (not the subrouter) to Build and Handle.

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{})
gen.Generate(ResponseData[User]{})

doc := gen.Document(openapi.Info{Title: "My Schemas", Version: "1.0.0"})
jsonBytes, _ := doc.JSON()
yamlBytes, _ := doc.YAML()

The resulting document contains openapi, info, and components.schemas. Named struct types and their transitive dependencies are included automatically.

Parsing documents

Use DocumentFromJSON or DocumentFromYAML to parse existing OpenAPI documents from serialized form:

jsonDoc, err := openapi.DocumentFromJSON(jsonBytes)
yamlDoc, err := openapi.DocumentFromYAML(yamlBytes)

Parsed documents can be inspected, modified, re-exported, or passed to MergeDocuments.

Merging documents

MergeDocuments combines multiple OpenAPI documents into a single unified document. This is useful in microservice architectures where each service produces its own spec:

merged, err := openapi.MergeDocuments(
    openapi.Info{Title: "Platform API", Version: "1.0.0"},
    usersDoc,
    billingDoc,
    notificationsDoc,
)
if err != nil {
    log.Fatal(err) // conflict details in error message
}
data, _ := merged.JSON()

Merge behavior:

Field Behavior
Paths Merged; duplicate path with different definition produces conflict error
Webhooks Merged; duplicate name with different definition produces conflict error
Components All 10 types merged; identical entries deduplicated, different entries produce conflict error
Tags Deduplicated by name; first non-empty description wins; sorted alphabetically
Security Union; deduplicated via JSON serialization
Servers Dropped (set on the returned document)

All conflicts are collected and returned in a single error (not fail-fast). Identical entries (compared via JSON serialization) are silently deduplicated.

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.

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

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Callback

type Callback map[string]*PathItem

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.

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

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.

See: https://spec.openapis.org/oas/v3.1.0#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.

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

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.

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

const (
	DocsSwaggerUI DocsUI = iota
	DocsRapiDoc
	DocsRedoc
)

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

func DocumentFromJSON(data []byte) (*Document, error)

DocumentFromJSON parses a JSON-encoded OpenAPI document.

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

func DocumentFromYAML added in v0.3.0

func DocumentFromYAML(data []byte) (*Document, error)

DocumentFromYAML parses a YAML-encoded OpenAPI document.

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

func MergeDocuments added in v0.3.0

func MergeDocuments(info Info, docs ...*Document) (*Document, error)

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).

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

func (*Document) JSON added in v0.3.0

func (d *Document) JSON() ([]byte, error)

JSON serializes the document as indented JSON bytes.

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

func (*Document) YAML added in v0.3.0

func (d *Document) YAML() ([]byte, error)

YAML serializes the document as YAML bytes.

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

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".

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

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.

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

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.

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

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".

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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 (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.

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

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.

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

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 (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

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.

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

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.

See: https://spec.openapis.org/oas/v3.1.0#path-item-object

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.

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

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.

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

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 (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.

See: https://spec.openapis.org/oas/v3.1.0#path-item-object

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()

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

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

type SecurityRequirement map[string][]string

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.

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

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 NewSpec

func NewSpec(info Info) *Spec

NewSpec creates a new spec builder with the given API info.

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

func (*Spec) AddComponentCallback

func (s *Spec) AddComponentCallback(name string, cb *Callback) *Spec

AddComponentCallback registers a reusable callback in components.

See: https://spec.openapis.org/oas/v3.1.0#components-object (callbacks)

func (*Spec) AddComponentExample

func (s *Spec) AddComponentExample(name string, ex *Example) *Spec

AddComponentExample registers a reusable example in components.

See: https://spec.openapis.org/oas/v3.1.0#components-object (examples)

func (*Spec) AddComponentHeader

func (s *Spec) AddComponentHeader(name string, h *Header) *Spec

AddComponentHeader registers a reusable header in components.

See: https://spec.openapis.org/oas/v3.1.0#components-object (headers)

func (s *Spec) AddComponentLink(name string, l *Link) *Spec

AddComponentLink registers a reusable link in components.

See: https://spec.openapis.org/oas/v3.1.0#components-object (links)

func (*Spec) AddComponentParameter

func (s *Spec) AddComponentParameter(name string, param *Parameter) *Spec

AddComponentParameter registers a reusable parameter in components.

See: https://spec.openapis.org/oas/v3.1.0#components-object (parameters)

func (*Spec) AddComponentPathItem

func (s *Spec) AddComponentPathItem(name string, pi *PathItem) *Spec

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

func (s *Spec) AddComponentResponse(name string, resp *Response) *Spec

AddComponentResponse registers a reusable response in components.

See: https://spec.openapis.org/oas/v3.1.0#components-object (responses)

func (*Spec) AddPathParameter

func (s *Spec) AddPathParameter(path string, param *Parameter) *Spec

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

func (s *Spec) AddPathServer(path string, server Server) *Spec

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

func (s *Spec) AddServer(server Server) *Spec

AddServer adds a server to the spec.

See: https://spec.openapis.org/oas/v3.1.0#openapi-object (servers)

func (*Spec) AddTag

func (s *Spec) AddTag(tag Tag) *Spec

AddTag adds a user-defined tag with optional description and external docs.

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

func (*Spec) Build

func (s *Spec) Build(r *mux.Router) *Document

Build walks the router and assembles a complete OpenAPI Document.

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

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.

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

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.

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

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.).

See: https://spec.openapis.org/oas/v3.1.0#path-item-object

func (*Spec) SetExternalDocs

func (s *Spec) SetExternalDocs(url, description string) *Spec

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

func (s *Spec) SetPathDescription(path, description string) *Spec

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

func (s *Spec) SetPathSummary(path, summary string) *Spec

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.

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

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.

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

Jump to

Keyboard shortcuts

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