Documentation
¶
Overview ¶
Package openapi provides OpenAPI 3.0.4 and 3.1.2 specification generation for Go applications.
This package enables automatic generation of OpenAPI specifications from Go code using struct tags and reflection. It provides a pure, stateless API for building specifications with minimal boilerplate.
Features ¶
- HTTP method constructors (GET, POST, PUT, etc.) for clean operation definitions
- Automatic parameter discovery from struct tags (query, path, header, cookie)
- Request/response body schema generation from Go types
- Swagger UI integration with customizable appearance
- Semantic operation ID generation based on HTTP method and path
- Support for security schemes (Bearer, API Key, OAuth2, OpenID Connect)
- Collision-resistant schema naming (pkgname.TypeName format)
- Built-in validation against official OpenAPI meta-schemas
- Standalone validator for external OpenAPI specifications
Quick Start ¶
import (
"context"
"net/http"
"rivaas.dev/openapi"
)
// Create OpenAPI configuration
cfg := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithInfoDescription("API description"),
openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
openapi.WithServer("http://localhost:8080", "Local development"),
)
// Define operations
ops := []openapi.Operation{
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithDescription("Retrieves a user by ID"),
openapi.WithResponse(http.StatusOK, UserResponse{}),
openapi.WithTags("users"),
openapi.WithSecurity("bearerAuth"),
),
openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
openapi.WithResponse(http.StatusCreated, UserResponse{}),
openapi.WithTags("users"),
),
}
// Generate OpenAPI specification
result, err := cfg.Generate(context.Background(), ops...)
if err != nil {
log.Fatal(err)
}
// Use result.JSON for the OpenAPI specification
Configuration vs Operations ¶
The package uses two distinct types of options, both with the With* prefix:
- API options configure the spec: WithTitle, WithServer, WithBearerAuth
- Operation options configure routes: WithSummary, WithDescription, WithResponse, WithTags
Example:
cfg := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"), // API option
)
openapi.GET("/users/:id",
openapi.WithSummary("Get user"), // Operation option
openapi.WithResponse(200, User{}), // Operation option
)
Auto-Discovery ¶
The package automatically discovers API parameters from struct tags compatible with the binding package:
- query: Query parameters
- params: Path parameters
- header: Header parameters
- cookie: Cookie parameters
- json: Request body fields
Example:
type GetUserRequest struct {
ID int `params:"id" doc:"User ID" example:"123"`
Expand string `query:"expand" doc:"Fields to expand" enum:"profile,settings"`
}
This automatically generates OpenAPI parameters without manual specification.
Schema Naming ¶
Component schema names use the format "pkgname.TypeName" to prevent cross-package type name collisions. For example, types from different packages with the same name (e.g., "api.User" and "models.User") will generate distinct schema names in the OpenAPI specification.
Operation IDs ¶
Operation IDs are automatically generated from HTTP method and path using semantic naming:
- GET /users -> getUsers
- GET /users/:id -> getUserById
- POST /users -> createUser
- PATCH /users/:id -> updateUserById
- PUT /users/:id -> replaceUserById
Custom operation IDs can be set using the WithOperationID option.
Validation ¶
Generated specifications can be validated against the official OpenAPI meta-schemas. Validation is opt-in to avoid performance overhead:
cfg := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithValidation(true), // Enable validation
)
result, err := cfg.Generate(context.Background(), ops...)
if err != nil {
log.Fatal(err) // Will fail if spec is invalid
}
The validate subpackage provides standalone validation for external OpenAPI specs:
import "rivaas.dev/openapi/validate"
// Validate any OpenAPI spec
specJSON, _ := os.ReadFile("openapi.json")
if err := validate.ValidateSpecJSON(specJSON); err != nil {
log.Fatal(err)
}
Example (Warnings) ¶
Example_warnings demonstrates how to work with warnings from spec generation.
package main
import (
"context"
"fmt"
"rivaas.dev/openapi"
"rivaas.dev/openapi/diag"
)
func main() {
// Create API targeting OpenAPI 3.0 with 3.1-only features
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithVersion(openapi.V30x),
openapi.WithInfoSummary("A modern API"), // 3.1-only feature
)
result, err := api.Generate(context.Background(),
openapi.GET("/health", openapi.WithResponse(200, map[string]string{})),
)
if err != nil {
panic(err)
}
// Simple warning check
if len(result.Warnings) > 0 {
fmt.Printf("Generated with %d warnings\n", len(result.Warnings))
}
// Type-safe warning check (requires diag import)
if result.Warnings.Has(diag.WarnDownlevelInfoSummary) {
fmt.Println("Info summary was dropped for OpenAPI 3.0 compatibility")
}
// Filter by category
downlevelWarnings := result.Warnings.FilterCategory(diag.CategoryDownlevel)
fmt.Printf("Downlevel warnings: %d\n", len(downlevelWarnings))
// Process warnings
result.Warnings.Each(func(w diag.Warning) {
fmt.Printf("[%s] %s\n", w.Code(), w.Message())
})
}
Output: Generated with 1 warnings Info summary was dropped for OpenAPI 3.0 compatibility Downlevel warnings: 1 [DOWNLEVEL_INFO_SUMMARY] info.summary is 3.1-only; dropped
Example (WarningsFiltering) ¶
Example_warningsFiltering demonstrates advanced warning filtering.
package main
import (
"context"
"fmt"
"rivaas.dev/openapi"
"rivaas.dev/openapi/diag"
)
func main() {
api := openapi.MustNew(
openapi.WithTitle("API", "1.0.0"),
openapi.WithVersion(openapi.V30x),
openapi.WithInfoSummary("Summary"), // 3.1 feature
openapi.WithLicenseIdentifier("MIT", "MIT-0"), // 3.1 feature
)
result, _ := api.Generate(context.Background(),
openapi.GET("/health", openapi.WithResponse(200, map[string]string{})),
)
// Get only specific warnings
licenseWarnings := result.Warnings.Filter(diag.WarnDownlevelLicenseIdentifier)
fmt.Printf("License warnings: %d\n", len(licenseWarnings))
// Exclude expected warnings
unexpected := result.Warnings.Exclude(diag.WarnDownlevelInfoSummary)
fmt.Printf("Unexpected warnings: %d\n", len(unexpected))
// Check for any of multiple codes
hasSecurityIssues := result.Warnings.HasAny(
diag.WarnDownlevelMutualTLS,
diag.WarnDownlevelWebhooks,
)
fmt.Printf("Has security issues: %v\n", hasSecurityIssues)
}
Output: License warnings: 1 Unexpected warnings: 1 Has security issues: false
Example (WarningsStrictMode) ¶
Example_warningsStrictMode demonstrates strict downlevel mode.
package main
import (
"context"
"fmt"
"rivaas.dev/openapi"
)
func main() {
// Strict mode treats downlevel issues as errors
api := openapi.MustNew(
openapi.WithTitle("API", "1.0.0"),
openapi.WithVersion(openapi.V30x),
openapi.WithStrictDownlevel(true), // Errors instead of warnings
openapi.WithInfoSummary("Summary"), // 3.1-only feature
)
_, err := api.Generate(context.Background(),
openapi.GET("/health", openapi.WithResponse(200, map[string]string{})),
)
// In strict mode, using 3.1 features with 3.0 target returns an error
if err != nil {
fmt.Printf("Error: %v\n", err)
}
}
Output: Error: failed to project OpenAPI spec: info.summary not supported in OpenAPI 3.0
Index ¶
- Constants
- Variables
- type API
- type DocExpansionMode
- type Example
- type ExampleOption
- type HTTPMethod
- type ModelRenderingMode
- type OAuth2Flow
- type OAuthFlowType
- type Operation
- func DELETE(path string, opts ...OperationOption) Operation
- func GET(path string, opts ...OperationOption) Operation
- func HEAD(path string, opts ...OperationOption) Operation
- func OPTIONS(path string, opts ...OperationOption) Operation
- func Op(method, path string, opts ...OperationOption) Operation
- func PATCH(path string, opts ...OperationOption) Operation
- func POST(path string, opts ...OperationOption) Operation
- func PUT(path string, opts ...OperationOption) Operation
- func TRACE(path string, opts ...OperationOption) Operation
- type OperationOption
- func WithConsumes(contentTypes ...string) OperationOption
- func WithDeprecated() OperationOption
- func WithDescription(s string) OperationOption
- func WithOperationExtension(key string, value any) OperationOption
- func WithOperationID(id string) OperationOption
- func WithOptions(opts ...OperationOption) OperationOption
- func WithProduces(contentTypes ...string) OperationOption
- func WithRequest(req any, examples ...example.Example) OperationOption
- func WithResponse(status int, resp any, examples ...example.Example) OperationOption
- func WithSecurity(scheme string, scopes ...string) OperationOption
- func WithSummary(s string) OperationOption
- func WithTags(tags ...string) OperationOption
- type OperationsSorterMode
- type Option
- func WithAPIKey(name, paramName string, in ParameterLocation, desc string) Option
- func WithBearerAuth(name, desc string) Option
- func WithContact(name, url, email string) Option
- func WithDefaultSecurity(scheme string, scopes ...string) Option
- func WithExtension(key string, value any) Option
- func WithExternalDocs(url, description string) Option
- func WithInfoDescription(desc string) Option
- func WithInfoExtension(key string, value any) Option
- func WithInfoSummary(summary string) Option
- func WithLicense(name, url string) Option
- func WithLicenseIdentifier(name, identifier string) Option
- func WithOAuth2(name, desc string, flows ...OAuth2Flow) Option
- func WithOpenIDConnect(name, url, desc string) Option
- func WithServer(url, desc string) Option
- func WithServerVariable(name, defaultValue string, enum []string, description string) Option
- func WithSpecPath(path string) Option
- func WithStrictDownlevel(strict bool) Option
- func WithSwaggerUI(path string, opts ...UIOption) Option
- func WithTag(name, desc string) Option
- func WithTermsOfService(url string) Option
- func WithTitle(title, version string) Option
- func WithValidation(enabled bool) Option
- func WithVersion(version Version) Option
- func WithoutSwaggerUI() Option
- type ParamSpec
- type ParameterLocation
- type RequestMetadata
- type RequestSnippetLanguage
- type RequestSnippetsConfig
- type Result
- type SecurityReq
- type SyntaxHighlightConfig
- type SyntaxTheme
- type TagsSorterMode
- type UIConfig
- type UIOption
- func WithUIDeepLinking(enabled bool) UIOption
- func WithUIDefaultModelRendering(mode ModelRenderingMode) UIOption
- func WithUIDisplayOperationID(show bool) UIOption
- func WithUIDisplayRequestDuration(show bool) UIOption
- func WithUIExpansion(mode DocExpansionMode) UIOption
- func WithUIFilter(enabled bool) UIOption
- func WithUIMaxDisplayedTags(max int) UIOption
- func WithUIModelExpandDepth(depth int) UIOption
- func WithUIModelsExpandDepth(depth int) UIOption
- func WithUIOperationsSorter(mode OperationsSorterMode) UIOption
- func WithUIPersistAuth(enabled bool) UIOption
- func WithUIRequestSnippets(enabled bool, languages ...RequestSnippetLanguage) UIOption
- func WithUIRequestSnippetsExpanded(expanded bool) UIOption
- func WithUIShowCommonExtensions(show bool) UIOption
- func WithUIShowExtensions(show bool) UIOption
- func WithUISupportedMethods(methods ...HTTPMethod) UIOption
- func WithUISyntaxHighlight(enabled bool) UIOption
- func WithUISyntaxTheme(theme SyntaxTheme) UIOption
- func WithUITagsSorter(mode TagsSorterMode) UIOption
- func WithUITryItOut(enabled bool) UIOption
- func WithUIValidator(url string) UIOption
- func WithUIWithCredentials(enabled bool) UIOption
- type Version
Examples ¶
Constants ¶
const ( // ValidatorLocal uses the embedded OpenAPI meta-schema for local validation. // No external service calls are made. This is the recommended option for // privacy, reliability, and offline support. ValidatorLocal = "local" // ValidatorNone disables Swagger UI validation entirely. ValidatorNone = "none" )
Validator URL constants for Swagger UI validation.
Variables ¶
var ( // ErrTitleRequired indicates the API title was not provided. ErrTitleRequired = errors.New("openapi: title is required") // ErrVersionRequired indicates the API version was not provided. ErrVersionRequired = errors.New("openapi: version is required") // ErrLicenseMutuallyExclusive indicates both license identifier and URL were set. ErrLicenseMutuallyExclusive = errors.New("openapi: license identifier and url are mutually exclusive") // ErrServerVariablesNeedURL indicates server variables were set without a server URL. ErrServerVariablesNeedURL = errors.New("openapi: server variables require a server URL") // ErrInvalidVersion indicates an unsupported OpenAPI version was specified. ErrInvalidVersion = errors.New("openapi: invalid OpenAPI version") )
Configuration Errors (returned by New)
var ( // ErrDuplicateOperationID indicates two operations have the same ID. ErrDuplicateOperationID = errors.New("openapi: duplicate operation ID") // ErrNoOperations indicates Generate was called with no operations. ErrNoOperations = errors.New("openapi: at least one operation is required") )
Generation Errors (returned by Generate)
var ( // ErrPathEmpty indicates an empty path was provided. ErrPathEmpty = errors.New("openapi: path cannot be empty") // ErrPathNoLeadingSlash indicates the path doesn't start with '/'. ErrPathNoLeadingSlash = errors.New("openapi: path must start with '/'") // ErrPathDuplicateParameter indicates a path parameter appears twice. ErrPathDuplicateParameter = errors.New("openapi: duplicate path parameter") // ErrPathInvalidParameter indicates an invalid path parameter format. ErrPathInvalidParameter = errors.New("openapi: invalid path parameter format") )
Path Errors
var ( // ErrInvalidExtensionKey indicates an extension key doesn't start with "x-". ErrInvalidExtensionKey = errors.New("openapi: extension key must start with 'x-'") // ErrReservedExtensionKey indicates an extension uses reserved prefix. ErrReservedExtensionKey = errors.New("openapi: extension key uses reserved prefix (x-oai- or x-oas-)") )
Extension Errors
var ( // ErrInvalidDocExpansion indicates an invalid docExpansion mode. ErrInvalidDocExpansion = errors.New("openapi: invalid docExpansion mode") // ErrInvalidDefaultModelRendering indicates an invalid defaultModelRendering mode. ErrInvalidDefaultModelRendering = errors.New("openapi: invalid defaultModelRendering mode") // ErrInvalidOperationsSorter indicates an invalid operationsSorter mode. ErrInvalidOperationsSorter = errors.New("openapi: invalid operationsSorter mode") // ErrInvalidTagsSorter indicates an invalid tagsSorter mode. ErrInvalidTagsSorter = errors.New("openapi: invalid tagsSorter mode") // ErrInvalidSyntaxTheme indicates an invalid syntax theme. ErrInvalidSyntaxTheme = errors.New("openapi: invalid syntax theme") )
UI Configuration Errors
var ( // ErrSpecValidationFailed indicates the generated spec failed JSON Schema validation. ErrSpecValidationFailed = errors.New("openapi: generated spec failed JSON Schema validation") )
Validation Errors (when WithValidation enabled)
var ( // ErrStrictDownlevelViolation indicates 3.1 features were used with 3.0 target // when strict mode is enabled. This error is opt-in via WithStrictDownlevel(true). ErrStrictDownlevelViolation = errors.New("openapi: 3.1 features used with 3.0 target in strict mode") )
Strict Mode Errors (opt-in via WithStrictDownlevel)
Functions ¶
This section is empty.
Types ¶
type API ¶ added in v0.4.0
type API struct {
// Info contains API metadata (title, version, description, contact, license).
Info model.Info
// Servers lists available server URLs for the API.
Servers []model.Server
// Tags provides additional metadata for operations.
Tags []model.Tag
// SecuritySchemes defines available authentication/authorization schemes.
SecuritySchemes map[string]*model.SecurityScheme
// DefaultSecurity applies security requirements to all operations by default.
DefaultSecurity []model.SecurityRequirement
// ExternalDocs provides external documentation links.
ExternalDocs *model.ExternalDocs
// Extensions contains specification extensions (fields prefixed with x-).
// Extensions are added to the root of the OpenAPI specification.
//
// Direct mutation of this map after New/MustNew bypasses API.Validate().
// However, projection-time filtering via copyExtensions still applies:
// - Keys must start with "x-"
// - In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved and will be filtered
//
// Prefer using WithExtension() option instead of direct mutation.
Extensions map[string]any
// Version is the target OpenAPI version.
// Use V30x or V31x constants.
// Default: V30x
Version Version
// StrictDownlevel causes projection to error (instead of warn) when
// 3.1-only features are used with a 3.0 target.
// Default: false
StrictDownlevel bool
// SpecPath is the HTTP path where the OpenAPI specification JSON is served.
// Default: "/openapi.json"
SpecPath string
// UIPath is the HTTP path where Swagger UI is served.
// Default: "/docs"
UIPath string
// ServeUI enables or disables Swagger UI serving.
// Default: true
ServeUI bool
// ValidateSpec enables JSON Schema validation of generated specs.
// When enabled, Generate validates the output against the official
// OpenAPI meta-schema (3.0.x or 3.1.x based on target version).
// This catches specification errors early but adds ~1-5ms overhead.
// Default: false
ValidateSpec bool
// contains filtered or unexported fields
}
API holds OpenAPI configuration and defines an API specification. All fields are public for functional options, but direct modification after creation is not recommended. Use functional options to configure.
Create instances using New or MustNew.
func MustNew ¶
MustNew creates a new OpenAPI API and panics if validation fails.
This is a convenience wrapper around New for use in package initialization or when configuration errors should cause immediate failure.
Example:
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithDescription("API description"),
)
Example ¶
ExampleMustNew demonstrates creating OpenAPI API definition that panics on error.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
func main() {
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithSwaggerUI("/docs"),
)
fmt.Printf("UI enabled: %v\n", api.ServeUI)
}
Output: UI enabled: true
func New ¶
New creates a new OpenAPI API with the given options.
It applies default values and validates the configuration. Returns an error if validation fails (e.g., missing title or version). Use API.Validate to check validation rules.
Example:
api, err := openapi.New(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithDescription("API description"),
openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
)
if err != nil {
log.Fatal(err)
}
Example ¶
ExampleNew demonstrates creating a new OpenAPI API definition.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
func main() {
api, err := openapi.New(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithInfoDescription("API for managing users"),
openapi.WithServer("http://localhost:8080", "Local development"),
)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Title: %s, Version: %s\n", api.Info.Title, api.Info.Version)
}
Output: Title: My API, Version: 1.0.0
func (*API) Generate ¶ added in v0.4.0
Generate produces an OpenAPI specification from operations.
This is a pure function with no side effects. It takes configuration and operations as input and produces JSON/YAML bytes as output. Caching and state management are the caller's responsibility.
Example:
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithBearerAuth("bearerAuth", "JWT"),
)
result, err := api.Generate(ctx,
openapi.GET("/users/:id",
openapi.Summary("Get user"),
openapi.Response(200, UserResponse{}),
),
openapi.POST("/users",
openapi.Summary("Create user"),
openapi.Request(CreateUserRequest{}),
openapi.Response(201, UserResponse{}),
),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(result.JSON))
Example ¶
ExampleAPI_Generate demonstrates generating an OpenAPI specification.
package main
import (
"context"
"fmt"
"rivaas.dev/openapi"
)
func main() {
api := openapi.MustNew(
openapi.WithTitle("User API", "1.0.0"),
)
// Generate the spec using HTTP method constructors
result, err := api.Generate(context.Background(),
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithDescription("Retrieves a user by ID"),
openapi.WithTags("users"),
),
)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Generated spec: %v\n", len(result.JSON) > 0)
}
Output: Generated spec: true
func (*API) UI ¶ added in v0.4.0
UI returns the Swagger UI configuration.
This provides access to UI settings for rendering the Swagger UI.
type DocExpansionMode ¶
type DocExpansionMode string
DocExpansionMode controls the default expansion behavior of operations and tags in Swagger UI.
This setting determines how much of the API documentation is expanded by default when the Swagger UI page loads.
const ( // DocExpansionList expands only tags by default, keeping operations collapsed. DocExpansionList DocExpansionMode = "list" // DocExpansionFull expands both tags and operations by default. DocExpansionFull DocExpansionMode = "full" // DocExpansionNone collapses everything by default, requiring manual expansion. DocExpansionNone DocExpansionMode = "none" )
DocExpansion constants control default expansion of operations and tags.
type Example ¶
type Example struct {
// contains filtered or unexported fields
}
Example represents an OpenAPI Example Object. Used for both request body and response body examples. See: https://spec.openapis.org/oas/v3.1.0#example-object
func ExternalExample ¶ added in v0.2.0
func ExternalExample(name, url string, opts ...ExampleOption) Example
ExternalExample creates a named example pointing to an external URL.
Use this for:
- Large examples that would bloat the spec
- Examples in formats that can't be embedded (XML, binary)
- Shared examples across multiple specs
Parameters:
- name: Unique identifier
- url: URL pointing to the example content
- opts: Optional configuration (summary, description)
Usage:
openapi.ExternalExample("large-response", "https://api.example.com/examples/large.json")
openapi.ExternalExample("xml-example", "https://api.example.com/examples/user.xml",
openapi.WithExampleSummary("XML format response"),
)
func NewExample ¶ added in v0.2.0
func NewExample(name string, value any, opts ...ExampleOption) Example
NewExample creates a named example with an inline value. Note: This is named NewExample instead of Example to avoid a naming conflict with the Example type. Go does not allow a type and function with the same name in the same package.
Parameters:
- name: Unique identifier (used as key in OpenAPI examples map)
- value: The example value (serialized to JSON in spec)
- opts: Optional configuration (summary, description)
Usage:
openapi.NewExample("success", UserResponse{ID: 123, Name: "John"})
openapi.NewExample("admin", UserResponse{ID: 1, Role: "admin"},
openapi.WithExampleSummary("Admin user response"),
)
func (Example) Description ¶
Description returns the detailed description.
func (Example) ExternalValue ¶
ExternalValue returns the URL to an external example.
func (Example) IsExternal ¶ added in v0.2.0
IsExternal returns true if this example uses an external URL.
type ExampleOption ¶ added in v0.2.0
type ExampleOption func(*Example)
ExampleOption is a functional option for configuring an Example.
func WithExampleDescription ¶ added in v0.2.0
func WithExampleDescription(description string) ExampleOption
WithExampleDescription sets a detailed description for the example. CommonMark syntax is supported for rich text formatting.
Usage:
openapi.NewExample("success", data,
openapi.WithExampleDescription("Returns when the user ID exists and is active."),
)
func WithExampleSummary ¶ added in v0.2.0
func WithExampleSummary(summary string) ExampleOption
WithExampleSummary sets a short description for the example. This appears as the example title in Swagger UI.
Usage:
openapi.NewExample("success", data,
openapi.WithExampleSummary("Successful response"),
)
type HTTPMethod ¶
type HTTPMethod string
HTTPMethod represents an HTTP method that can be used in "Try it out" functionality.
This is used to configure which HTTP methods are supported for interactive API testing.
const ( // MethodGet represents the HTTP GET method. MethodGet HTTPMethod = "get" // MethodPost represents the HTTP POST method. MethodPost HTTPMethod = "post" // MethodPut represents the HTTP PUT method. MethodPut HTTPMethod = "put" // MethodDelete represents the HTTP DELETE method. MethodDelete HTTPMethod = "delete" // MethodPatch represents the HTTP PATCH method. MethodPatch HTTPMethod = "patch" // MethodHead represents the HTTP HEAD method. MethodHead HTTPMethod = "head" // MethodOptions represents the HTTP OPTIONS method. MethodOptions HTTPMethod = "options" // MethodTrace represents the HTTP TRACE method. MethodTrace HTTPMethod = "trace" )
HTTP method constants for "Try it out" configuration.
type ModelRenderingMode ¶
type ModelRenderingMode string
ModelRenderingMode controls how schema models are initially displayed in Swagger UI.
Models can be shown as example values or as structured schema definitions.
const ( // ModelRenderingExample shows example values for schema models. ModelRenderingExample ModelRenderingMode = "example" // ModelRenderingModel shows the structured schema definition. ModelRenderingModel ModelRenderingMode = "model" )
ModelRendering constants control initial model display.
type OAuth2Flow ¶
type OAuth2Flow struct {
// Type specifies the OAuth2 flow type (implicit, password, clientCredentials, authorizationCode).
Type OAuthFlowType
// AuthorizationURL is required for implicit and authorizationCode flows.
AuthorizationURL string
// TokenURL is required for password, clientCredentials, and authorizationCode flows.
TokenURL string
// RefreshURL is optional for all flows.
RefreshURL string
// Scopes maps scope names to descriptions (required, can be empty).
Scopes map[string]string
}
OAuth2Flow configures a single OAuth2 flow with explicit type.
type OAuthFlowType ¶
type OAuthFlowType string
OAuthFlowType represents the type of OAuth2 flow.
const ( // FlowImplicit represents the OAuth2 implicit flow. FlowImplicit OAuthFlowType = "implicit" // FlowPassword represents the OAuth2 resource owner password flow. FlowPassword OAuthFlowType = "password" // FlowClientCredentials represents the OAuth2 client credentials flow. FlowClientCredentials OAuthFlowType = "clientCredentials" // FlowAuthorizationCode represents the OAuth2 authorization code flow. FlowAuthorizationCode OAuthFlowType = "authorizationCode" )
type Operation ¶
type Operation struct {
Method string // HTTP method (GET, POST, etc.)
Path string // URL path with parameters (e.g. "/users/:id")
// contains filtered or unexported fields
}
Operation represents an OpenAPI operation (HTTP method + path + metadata). Create operations using the HTTP method constructors: GET, POST, PUT, PATCH, DELETE, etc.
func DELETE ¶ added in v0.4.0
func DELETE(path string, opts ...OperationOption) Operation
DELETE creates an Operation for a DELETE request.
Example:
openapi.DELETE("/users/:id",
openapi.WithSummary("Delete user"),
openapi.WithResponse(204, nil),
)
Example ¶
ExampleDELETE demonstrates creating a DELETE operation.
package main
import (
"fmt"
"net/http"
"rivaas.dev/openapi"
)
func main() {
op := openapi.DELETE("/users/:id",
openapi.WithSummary("Delete user"),
openapi.WithResponse(http.StatusNoContent, nil),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: DELETE, Path: /users/:id
func GET ¶ added in v0.4.0
func GET(path string, opts ...OperationOption) Operation
GET creates an Operation for a GET request.
Example:
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
)
Example ¶
ExampleGET demonstrates creating a GET operation.
package main
import (
"fmt"
"net/http"
"rivaas.dev/openapi"
)
func main() {
op := openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithDescription("Retrieves a user by ID"),
openapi.WithResponse(http.StatusOK, User{}),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
// User is an example type for documentation.
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
Output: Method: GET, Path: /users/:id
func HEAD ¶ added in v0.4.0
func HEAD(path string, opts ...OperationOption) Operation
HEAD creates an Operation for a HEAD request.
Example:
openapi.HEAD("/users/:id",
openapi.WithSummary("Check user exists"),
)
func OPTIONS ¶ added in v0.4.0
func OPTIONS(path string, opts ...OperationOption) Operation
OPTIONS creates an Operation for an OPTIONS request.
Example:
openapi.OPTIONS("/users",
openapi.WithSummary("Get supported methods"),
)
func Op ¶ added in v0.4.0
func Op(method, path string, opts ...OperationOption) Operation
Op creates an Operation with a custom HTTP method. Prefer using the method-specific constructors (GET, POST, etc.) when possible.
Example:
openapi.Op("CUSTOM", "/resource",
openapi.WithSummary("Custom operation"),
)
func PATCH ¶ added in v0.4.0
func PATCH(path string, opts ...OperationOption) Operation
PATCH creates an Operation for a PATCH request.
Example:
openapi.PATCH("/users/:id",
openapi.WithSummary("Partially update user"),
openapi.WithRequest(PatchUserRequest{}),
openapi.WithResponse(200, User{}),
)
func POST ¶ added in v0.4.0
func POST(path string, opts ...OperationOption) Operation
POST creates an Operation for a POST request.
Example:
openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
openapi.WithResponse(201, User{}),
)
Example ¶
ExamplePOST demonstrates creating a POST operation.
package main
import (
"fmt"
"net/http"
"rivaas.dev/openapi"
)
func main() {
op := openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
openapi.WithResponse(http.StatusCreated, User{}),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
// User is an example type for documentation.
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
// CreateUserRequest is an example request type.
type CreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}
Output: Method: POST, Path: /users
func PUT ¶ added in v0.4.0
func PUT(path string, opts ...OperationOption) Operation
PUT creates an Operation for a PUT request.
Example:
openapi.PUT("/users/:id",
openapi.WithSummary("Update user"),
openapi.WithRequest(UpdateUserRequest{}),
openapi.WithResponse(200, User{}),
)
func TRACE ¶ added in v0.4.0
func TRACE(path string, opts ...OperationOption) Operation
TRACE creates an Operation for a TRACE request.
Example:
openapi.TRACE("/users/:id",
openapi.WithSummary("Trace request"),
)
type OperationOption ¶ added in v0.4.0
type OperationOption func(*operationDoc)
OperationOption configures an OpenAPI operation. Use with HTTP method constructors like GET, POST, PUT, etc.
func WithConsumes ¶ added in v0.4.0
func WithConsumes(contentTypes ...string) OperationOption
WithConsumes sets the content types that this operation accepts.
Example:
openapi.POST("/users",
openapi.WithConsumes("application/xml", "application/json"),
)
func WithDeprecated ¶ added in v0.4.0
func WithDeprecated() OperationOption
WithDeprecated marks the operation as deprecated.
Example:
openapi.GET("/old-endpoint",
openapi.WithDeprecated(),
)
Example ¶
ExampleWithDeprecated demonstrates marking an operation as deprecated.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
func main() {
op := openapi.GET("/old-endpoint",
openapi.WithSummary("Old endpoint"),
openapi.WithDeprecated(),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: GET, Path: /old-endpoint
func WithDescription ¶
func WithDescription(s string) OperationOption
WithDescription sets the operation description.
Example:
openapi.GET("/users/:id",
openapi.WithDescription("Retrieves a user by their unique identifier"),
)
func WithOperationExtension ¶ added in v0.4.0
func WithOperationExtension(key string, value any) OperationOption
WithOperationExtension adds a specification extension to the operation.
Extension keys MUST start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved for the OpenAPI Initiative.
Example:
openapi.GET("/users/:id",
openapi.WithOperationExtension("x-rate-limit", 100),
openapi.WithOperationExtension("x-internal", true),
)
func WithOperationID ¶ added in v0.4.0
func WithOperationID(id string) OperationOption
WithOperationID sets a custom operation ID.
Example:
openapi.GET("/users/:id",
openapi.WithOperationID("getUserById"),
)
func WithOptions ¶ added in v0.4.0
func WithOptions(opts ...OperationOption) OperationOption
WithOptions composes multiple OperationOptions into a single option.
This enables creating reusable option sets for common patterns across operations. Options are applied in the order they are provided, with later options potentially overriding values set by earlier options.
Example:
// Define reusable option sets
var (
CommonErrors = openapi.WithOptions(
openapi.WithResponse(400, Error{}),
openapi.WithResponse(401, Error{}),
openapi.WithResponse(500, Error{}),
)
AuthRequired = openapi.WithOptions(
openapi.WithSecurity("jwt"),
)
UserEndpoint = openapi.WithOptions(
openapi.WithTags("users"),
AuthRequired,
CommonErrors,
)
)
// Apply composed options to operations
openapi.GET("/users/:id",
UserEndpoint,
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
)
openapi.POST("/users",
UserEndpoint,
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUser{}),
openapi.WithResponse(201, User{}),
)
func WithProduces ¶ added in v0.4.0
func WithProduces(contentTypes ...string) OperationOption
WithProduces sets the content types that this operation returns.
Example:
openapi.GET("/users/:id",
openapi.WithProduces("application/xml", "application/json"),
)
func WithRequest ¶ added in v0.4.0
func WithRequest(req any, examples ...example.Example) OperationOption
WithRequest sets the request type and optionally provides examples.
Example:
openapi.POST("/users",
openapi.WithRequest(CreateUserRequest{}),
)
Example ¶
ExampleWithRequest demonstrates setting request schemas.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
// CreateUserRequest is an example request type.
type CreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
op := openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: POST, Path: /users
func WithResponse ¶ added in v0.4.0
func WithResponse(status int, resp any, examples ...example.Example) OperationOption
WithResponse sets the response schema and examples for a status code.
Example:
openapi.GET("/users/:id",
openapi.WithResponse(200, User{}),
openapi.WithResponse(404, ErrorResponse{}),
)
Example ¶
ExampleWithResponse demonstrates setting response schemas.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
// User is an example type for documentation.
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
op := openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: GET, Path: /users/:id
func WithSecurity ¶ added in v0.4.0
func WithSecurity(scheme string, scopes ...string) OperationOption
WithSecurity adds a security requirement.
Example:
openapi.GET("/users/:id",
openapi.WithSecurity("bearerAuth"),
)
openapi.POST("/users",
openapi.WithSecurity("oauth2", "read:users", "write:users"),
)
Example ¶
ExampleWithSecurity demonstrates adding security requirements.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
func main() {
op := openapi.GET("/users/:id",
openapi.WithSecurity("bearerAuth"),
openapi.WithSecurity("oauth2", "read:users", "write:users"),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: GET, Path: /users/:id
func WithSummary ¶
func WithSummary(s string) OperationOption
WithSummary sets the operation summary.
Example:
openapi.GET("/users/:id",
openapi.WithSummary("Get user by ID"),
)
Example ¶
ExampleWithSummary demonstrates setting an operation summary.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
func main() {
op := openapi.GET("/users",
openapi.WithSummary("List all users"),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: GET, Path: /users
func WithTags ¶ added in v0.4.0
func WithTags(tags ...string) OperationOption
WithTags adds tags to the operation.
Example:
openapi.GET("/users/:id",
openapi.WithTags("users", "authentication"),
)
Example ¶
ExampleWithTags demonstrates adding tags to an operation.
package main
import (
"fmt"
"rivaas.dev/openapi"
)
func main() {
op := openapi.GET("/users/:id",
openapi.WithTags("users", "admin"),
)
fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output: Method: GET, Path: /users/:id
type OperationsSorterMode ¶
type OperationsSorterMode string
OperationsSorterMode controls how operations are sorted within each tag in Swagger UI.
Operations can be sorted alphabetically by path, by HTTP method, or left in server order.
const ( // OperationsSorterAlpha sorts operations alphabetically by path. OperationsSorterAlpha OperationsSorterMode = "alpha" // OperationsSorterMethod sorts operations by HTTP method. OperationsSorterMethod OperationsSorterMode = "method" // OperationsSorterNone uses server order without sorting. OperationsSorterNone OperationsSorterMode = "" )
OperationsSorter constants control operation sorting within tags.
type Option ¶
type Option func(*API)
Option configures OpenAPI behavior using the functional options pattern. Options are applied in order, with later options potentially overriding earlier ones.
func WithAPIKey ¶
func WithAPIKey(name, paramName string, in ParameterLocation, desc string) Option
WithAPIKey adds API key authentication scheme.
Parameters:
- name: Scheme name used in security requirements
- paramName: Name of the header/query parameter (e.g., "X-API-Key")
- in: Location of the API key - use InHeader, InQuery, or InCookie
- desc: Description shown in Swagger UI
Example:
openapi.WithAPIKey("apiKey", "X-API-Key", openapi.InHeader, "API key in X-API-Key header")
func WithBearerAuth ¶
WithBearerAuth adds Bearer (JWT) authentication scheme.
The name is used to reference this scheme in security requirements. The description appears in Swagger UI to help users understand the authentication.
Example:
openapi.WithBearerAuth("bearerAuth", "JWT token authentication. Format: Bearer <token>")
Then use in routes:
app.GET("/protected", handler).Bearer()
func WithContact ¶
WithContact sets contact information for the API.
All parameters are optional. Empty strings are omitted from the specification.
Example:
openapi.WithContact("API Support", "https://example.com/support", "[email protected]")
func WithDefaultSecurity ¶
WithDefaultSecurity sets default security requirements applied to all operations.
Operations can override this by specifying their own security requirements using RouteWrapper.Security() or RouteWrapper.Bearer().
Example:
// Apply Bearer auth to all operations by default
openapi.WithDefaultSecurity("bearerAuth")
// Apply OAuth with specific scopes
openapi.WithDefaultSecurity("oauth2", "read", "write")
func WithExtension ¶
WithExtension adds a specification extension to the root OpenAPI specification.
Extension keys MUST start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved for the OpenAPI Initiative.
The value can be any valid JSON value (null, primitive, array, or object). Validation of extension keys happens during API.Validate().
Example:
openapi.WithExtension("x-internal-id", "api-v2")
openapi.WithExtension("x-code-samples", []map[string]any{
{"lang": "curl", "source": "curl https://api.example.com/users"},
})
func WithExternalDocs ¶
WithExternalDocs sets external documentation URL and optional description.
func WithInfoDescription ¶ added in v0.4.0
WithInfoDescription sets the API description in the Info object.
The description supports Markdown formatting and appears in the OpenAPI spec and Swagger UI.
Example:
openapi.WithInfoDescription("A RESTful API for managing users and their profiles.")
func WithInfoExtension ¶
WithInfoExtension adds a specification extension to the Info object.
Extension keys must start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved and cannot be used.
Example:
openapi.WithInfoExtension("x-api-category", "public")
func WithInfoSummary ¶ added in v0.4.0
WithInfoSummary sets the API summary in the Info object (OpenAPI 3.1+ only). In 3.0 targets, this will be dropped with a warning.
Example:
openapi.WithInfoSummary("User Management API")
func WithLicense ¶
WithLicense sets license information for the API using a URL (OpenAPI 3.0 style).
The name is required. URL is optional. This is mutually exclusive with identifier - use WithLicenseIdentifier for SPDX identifiers. Validation occurs when New() is called.
Example:
openapi.WithLicense("MIT", "https://opensource.org/licenses/MIT")
func WithLicenseIdentifier ¶
WithLicenseIdentifier sets license information for the API using an SPDX identifier (OpenAPI 3.1+).
The name is required. Identifier is an SPDX license expression (e.g., "Apache-2.0"). This is mutually exclusive with URL - use WithLicense for URL-based licenses. Validation occurs when New() is called.
Example:
openapi.WithLicenseIdentifier("Apache 2.0", "Apache-2.0")
func WithOAuth2 ¶
func WithOAuth2(name, desc string, flows ...OAuth2Flow) Option
WithOAuth2 adds OAuth2 authentication scheme.
At least one flow must be configured. Use OAuth2Flow to configure each flow type. Multiple flows can be provided to support different OAuth2 flow types.
Example:
openapi.WithOAuth2("oauth2", "OAuth2 authentication",
openapi.OAuth2Flow{
Type: openapi.FlowAuthorizationCode,
AuthorizationURL: "https://example.com/oauth/authorize",
TokenURL: "https://example.com/oauth/token",
Scopes: map[string]string{
"read": "Read access",
"write": "Write access",
},
},
openapi.OAuth2Flow{
Type: openapi.FlowClientCredentials,
TokenUrl: "https://example.com/oauth/token",
Scopes: map[string]string{"read": "Read access"},
},
)
func WithOpenIDConnect ¶
WithOpenIDConnect adds OpenID Connect authentication scheme.
Parameters:
- name: Scheme name used in security requirements
- url: Well-known URL to discover OpenID Connect provider metadata
- desc: Description shown in Swagger UI
Example:
openapi.WithOpenIDConnect("oidc", "https://example.com/.well-known/openid-configuration", "OpenID Connect authentication")
func WithServer ¶
WithServer adds a server URL to the specification.
Multiple servers can be added by calling this option multiple times. The description is optional and helps distinguish between environments.
Example:
openapi.WithServer("https://api.example.com", "Production"),
openapi.WithServer("https://staging-api.example.com", "Staging"),
func WithServerVariable ¶
WithServerVariable adds a variable to the last added server for URL template substitution.
The variable name should match a placeholder in the server URL (e.g., {username}). Default is required. Enum and description are optional.
IMPORTANT: WithServerVariable must be called AFTER WithServer. It applies to the most recently added server. Validation occurs when New() is called.
Example:
openapi.WithServer("https://{username}.example.com:{port}/v1", "Multi-tenant API"),
openapi.WithServerVariable("username", "demo", []string{"demo", "prod"}, "User subdomain"),
openapi.WithServerVariable("port", "8443", []string{"8443", "443"}, "Server port"),
func WithSpecPath ¶
WithSpecPath sets the HTTP path where the OpenAPI specification JSON is served.
Default: "/openapi.json"
Example:
openapi.WithSpecPath("/api/openapi.json")
func WithStrictDownlevel ¶
WithStrictDownlevel causes projection to error (instead of warn) when 3.1-only features are used with a 3.0 target.
Default: false (warnings only)
Example:
openapi.WithStrictDownlevel(true)
func WithSwaggerUI ¶
WithSwaggerUI enables Swagger UI at the given path with optional configuration.
The path parameter specifies where the Swagger UI will be served (e.g., "/docs"). UI options can be provided to customize the appearance and behavior.
Example:
openapi.MustNew(
openapi.WithTitle("API", "1.0.0"),
openapi.WithSwaggerUI("/docs",
openapi.WithUIExpansion(openapi.ExpandList),
openapi.WithUITryItOut(true),
openapi.WithUISyntaxTheme(openapi.Monokai),
),
)
func WithTag ¶
WithTag adds a tag to the specification.
Tags are used to group operations in Swagger UI. Operations can be assigned tags using RouteWrapper.Tags(). Multiple tags can be added by calling this option multiple times.
Example:
openapi.WithTag("users", "User management operations"),
openapi.WithTag("orders", "Order processing operations"),
func WithTermsOfService ¶
WithTermsOfService sets the Terms of Service URL/URI.
func WithTitle ¶
WithTitle sets the API title and version.
Both title and version are required. If not set, defaults to "API" and "1.0.0".
Example:
openapi.WithTitle("User Management API", "2.1.0")
func WithValidation ¶ added in v0.4.0
WithValidation enables or disables JSON Schema validation of the generated OpenAPI spec.
When enabled, Generate() validates the output against the official OpenAPI meta-schema and returns an error if the spec is invalid.
This is useful for:
- Development: Catch spec generation bugs early
- CI/CD: Ensure generated specs are valid before deployment
- Testing: Verify spec correctness in tests
Performance: Adds ~1-5ms overhead per generation. The default is false for backward compatibility. Enable for development and testing to catch errors early.
Default: false
Example:
openapi.WithValidation(false) // Disable for performance
func WithVersion ¶
WithVersion sets the target OpenAPI version.
Use V30x or V31x constants. Default: V30x
Example:
openapi.WithVersion(openapi.V31x)
func WithoutSwaggerUI ¶ added in v0.4.0
func WithoutSwaggerUI() Option
WithoutSwaggerUI disables Swagger UI serving.
Example:
openapi.MustNew(
openapi.WithTitle("API", "1.0.0"),
openapi.WithoutSwaggerUI(),
)
type ParamSpec ¶
ParamSpec describes a single parameter extracted from struct tags.
This is a type alias for the internal schema.ParamSpec type.
type ParameterLocation ¶
type ParameterLocation string
ParameterLocation represents where an API parameter can be located.
const ( // InHeader indicates the parameter is passed in the HTTP header. InHeader ParameterLocation = "header" // InQuery indicates the parameter is passed as a query string parameter. InQuery ParameterLocation = "query" // InCookie indicates the parameter is passed as a cookie. InCookie ParameterLocation = "cookie" )
type RequestMetadata ¶
type RequestMetadata = schema.RequestMetadata
RequestMetadata contains auto-discovered information about a request struct.
This is a type alias for the internal schema.RequestMetadata type.
type RequestSnippetLanguage ¶
type RequestSnippetLanguage string
RequestSnippetLanguage defines the language for generated request code snippets.
These snippets help users understand how to make API calls using different tools.
const ( // SnippetCurlBash generates curl commands for bash/sh shells. SnippetCurlBash RequestSnippetLanguage = "curl_bash" // SnippetCurlPowerShell generates curl commands for PowerShell. SnippetCurlPowerShell RequestSnippetLanguage = "curl_powershell" // SnippetCurlCmd generates curl commands for Windows CMD. SnippetCurlCmd RequestSnippetLanguage = "curl_cmd" )
Request snippet language constants.
type RequestSnippetsConfig ¶
type RequestSnippetsConfig struct {
// Languages specifies which snippet languages to generate.
// If empty, all available languages are included.
Languages []RequestSnippetLanguage
// DefaultExpanded determines if snippet sections are expanded by default.
DefaultExpanded bool
}
RequestSnippetsConfig controls code snippet generation for API requests.
type Result ¶ added in v0.4.0
type Result struct {
// JSON is the OpenAPI spec serialized as JSON.
JSON []byte
// YAML is the OpenAPI spec serialized as YAML.
YAML []byte
// Warnings contains informational, non-fatal issues.
// These are advisory only and do not indicate failure.
// The spec in JSON/YAML is valid even when warnings exist.
//
// Import "rivaas.dev/openapi/diag" for type-safe warning code checks.
Warnings diag.Warnings
}
Result contains the generated OpenAPI specification.
type SecurityReq ¶
SecurityReq represents a security requirement for an operation.
type SyntaxHighlightConfig ¶
type SyntaxHighlightConfig struct {
// Activated enables or disables syntax highlighting.
Activated bool
// Theme specifies the color scheme for syntax highlighting.
Theme SyntaxTheme
}
SyntaxHighlightConfig controls syntax highlighting appearance in Swagger UI.
type SyntaxTheme ¶
type SyntaxTheme string
SyntaxTheme defines the syntax highlighting theme used for code examples in Swagger UI.
Different themes provide different color schemes for code snippets and examples.
const ( // SyntaxThemeAgate provides a dark theme with blue accents. SyntaxThemeAgate SyntaxTheme = "agate" // SyntaxThemeArta provides a dark theme with orange accents. SyntaxThemeArta SyntaxTheme = "arta" // SyntaxThemeMonokai provides a dark theme with vibrant colors. SyntaxThemeMonokai SyntaxTheme = "monokai" // SyntaxThemeNord provides a dark theme with cool blue tones. SyntaxThemeNord SyntaxTheme = "nord" // SyntaxThemeObsidian provides a dark theme with green accents. SyntaxThemeObsidian SyntaxTheme = "obsidian" // SyntaxThemeTomorrowNight provides a dark theme with muted colors. SyntaxThemeTomorrowNight SyntaxTheme = "tomorrow-night" // SyntaxThemeIdea provides a light theme similar to IntelliJ IDEA. SyntaxThemeIdea SyntaxTheme = "idea" )
Syntax highlighting theme constants.
type TagsSorterMode ¶
type TagsSorterMode string
TagsSorterMode controls how tags are sorted in Swagger UI.
Tags can be sorted alphabetically or left in server order.
const ( // TagsSorterAlpha sorts tags alphabetically. TagsSorterAlpha TagsSorterMode = "alpha" // TagsSorterNone uses server order without sorting. TagsSorterNone TagsSorterMode = "" )
TagsSorter constants control tag sorting.
type UIConfig ¶ added in v0.4.0
type UIConfig struct {
// Navigation & Deep Linking
DeepLinking bool
DisplayOperationID bool
// Display & Expansion
DocExpansion DocExpansionMode
DefaultModelsExpandDepth int
DefaultModelExpandDepth int
DefaultModelRendering ModelRenderingMode
// Interaction
TryItOutEnabled bool
RequestSnippetsEnabled bool
DisplayRequestDuration bool
// Filtering & Sorting
Filter bool
MaxDisplayedTags int
OperationsSorter OperationsSorterMode
TagsSorter TagsSorterMode
// Syntax Highlighting
SyntaxHighlight SyntaxHighlightConfig
// Network & Security
ValidatorURL string
PersistAuthorization bool
WithCredentials bool
SupportedSubmitMethods []HTTPMethod
// Advanced
ShowExtensions bool
ShowCommonExtensions bool
// Request Snippets Configuration
RequestSnippets RequestSnippetsConfig
}
UIConfig configures Swagger UI behavior and appearance.
This type is used internally to build the JavaScript configuration object that controls how Swagger UI renders and behaves.
func (*UIConfig) ToConfigMap ¶ added in v0.4.0
ToConfigMap converts UIConfig to a map suitable for JSON serialization.
The returned map contains all configuration options in the format expected by Swagger UI's JavaScript initialization. The specURL parameter specifies the URL where the OpenAPI specification JSON can be fetched.
This method is used internally to generate the JavaScript configuration object that is embedded in the Swagger UI HTML page.
func (*UIConfig) ToJSON ¶ added in v0.4.0
ToJSON converts UIConfig to a formatted JSON string for embedding in HTML.
The returned JSON string is indented for readability and can be directly embedded in the Swagger UI HTML template. The specURL parameter specifies the URL where the OpenAPI specification JSON can be fetched.
Returns an error if JSON serialization fails.
func (*UIConfig) Validate ¶ added in v0.4.0
Validate checks if the UIConfig is valid and returns an error if any configuration values are invalid.
It validates:
- DocExpansion mode (must be list, full, or none)
- ModelRendering mode (must be example or model)
- OperationsSorter mode (must be alpha, method, or empty)
- TagsSorter mode (must be alpha or empty)
- SyntaxTheme (must be a valid theme name)
- RequestSnippetLanguage values (must be valid language identifiers)
- HTTPMethod values (must be valid HTTP methods)
- Numeric ranges (depths must be >= -1, maxDisplayedTags must be >= 0)
type UIOption ¶ added in v0.4.0
type UIOption func(*UIConfig)
UIOption configures Swagger UI behavior and appearance.
func WithUIDeepLinking ¶
WithUIDeepLinking enables or disables deep linking in Swagger UI.
When enabled, Swagger UI updates the browser URL when operations are expanded, allowing direct linking to specific operations. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIDeepLinking(true),
)
func WithUIDefaultModelRendering ¶
func WithUIDefaultModelRendering(mode ModelRenderingMode) UIOption
WithUIDefaultModelRendering sets the initial model display mode.
Valid modes:
- ModelRenderingExample: Show example value (default)
- ModelRenderingModel: Show model structure
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIDefaultModelRendering(openapi.ModelRenderingModel),
)
func WithUIDisplayOperationID ¶
WithUIDisplayOperationID shows or hides operation IDs in Swagger UI.
Operation IDs are useful for code generation and API client libraries. Default: false.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIDisplayOperationID(true),
)
func WithUIDisplayRequestDuration ¶
WithUIDisplayRequestDuration shows or hides request duration in Swagger UI.
When enabled, the time taken for "Try it out" requests is displayed. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIDisplayRequestDuration(true),
)
func WithUIExpansion ¶ added in v0.4.0
func WithUIExpansion(mode DocExpansionMode) UIOption
WithUIExpansion sets the default expansion level for operations and tags.
Valid modes:
- ExpandList: Expand only tags (default)
- ExpandFull: Expand tags and operations
- ExpandNone: Collapse everything
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIExpansion(openapi.ExpandFull),
)
func WithUIFilter ¶
WithUIFilter enables or disables the operation filter/search box.
When enabled, users can filter operations by typing in a search box. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIFilter(true),
)
func WithUIMaxDisplayedTags ¶
WithUIMaxDisplayedTags limits the number of tags displayed in Swagger UI.
When set to a positive number, only the first N tags are shown. Remaining tags are hidden. Use 0 or negative to show all tags. Default: 0 (show all).
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIMaxDisplayedTags(10), // Show only first 10 tags
)
func WithUIModelExpandDepth ¶
WithUIModelExpandDepth sets the default expansion depth for model example sections.
Controls how many levels of the example value are expanded. Default: 1.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIModelExpandDepth(3),
)
func WithUIModelsExpandDepth ¶
WithUIModelsExpandDepth sets the default expansion depth for model schemas.
Depth controls how many levels of nested properties are expanded by default. Use -1 to hide models completely. Default: 1.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIModelsExpandDepth(2), // Expand 2 levels deep
)
func WithUIOperationsSorter ¶
func WithUIOperationsSorter(mode OperationsSorterMode) UIOption
WithUIOperationsSorter sets how operations are sorted within tags.
Valid modes:
- OperationsSorterAlpha: Sort alphabetically by path
- OperationsSorterMethod: Sort by HTTP method (GET, POST, etc.)
- OperationsSorterNone: Use server order (no sorting, default)
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIOperationsSorter(openapi.OperationsSorterAlpha),
)
func WithUIPersistAuth ¶
WithUIPersistAuth enables or disables authorization persistence.
When enabled, authorization tokens are persisted in browser storage and automatically included in subsequent requests. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIPersistAuth(true),
)
func WithUIRequestSnippets ¶
func WithUIRequestSnippets(enabled bool, languages ...RequestSnippetLanguage) UIOption
WithUIRequestSnippets enables or disables code snippet generation.
When enabled, Swagger UI generates code snippets showing how to call the API in various languages (curl, etc.). The languages parameter specifies which snippet generators to include. If not provided, defaults to curl_bash.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIRequestSnippets(true, openapi.SnippetCurlBash, openapi.SnippetCurlPowerShell),
)
func WithUIRequestSnippetsExpanded ¶
WithUIRequestSnippetsExpanded sets whether request snippets are expanded by default.
When true, code snippets are shown immediately without requiring user interaction. Default: false.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIRequestSnippetsExpanded(true),
)
func WithUIShowCommonExtensions ¶
WithUIShowCommonExtensions shows or hides common JSON Schema extensions.
When enabled, displays schema constraints like pattern, maxLength, minLength, etc. in the UI. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIShowCommonExtensions(true),
)
func WithUIShowExtensions ¶
WithUIShowExtensions shows or hides vendor extensions (x-* fields) in Swagger UI.
Vendor extensions are custom fields prefixed with "x-" in the OpenAPI spec. Default: false.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIShowExtensions(true),
)
func WithUISupportedMethods ¶
func WithUISupportedMethods(methods ...HTTPMethod) UIOption
WithUISupportedMethods sets which HTTP methods have "Try it out" enabled.
By default, all standard HTTP methods support "Try it out". Use this option to restrict which methods can be tested interactively in Swagger UI.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUISupportedMethods(openapi.MethodGet, openapi.MethodPost),
)
func WithUISyntaxHighlight ¶
WithUISyntaxHighlight enables or disables syntax highlighting in Swagger UI.
When enabled, request/response examples and code snippets are syntax-highlighted using the configured theme. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUISyntaxHighlight(true),
)
func WithUISyntaxTheme ¶
func WithUISyntaxTheme(theme SyntaxTheme) UIOption
WithUISyntaxTheme sets the syntax highlighting theme for code examples.
Available themes: Agate, Arta, Monokai, Nord, Obsidian, TomorrowNight, Idea. Default: Agate.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUISyntaxTheme(openapi.SyntaxThemeMonokai),
)
func WithUITagsSorter ¶
func WithUITagsSorter(mode TagsSorterMode) UIOption
WithUITagsSorter sets how tags are sorted in Swagger UI.
Valid modes:
- TagsSorterAlpha: Sort tags alphabetically
- TagsSorterNone: Use server order (no sorting, default)
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUITagsSorter(openapi.TagsSorterAlpha),
)
func WithUITryItOut ¶
WithUITryItOut enables or disables "Try it out" functionality by default.
When enabled, the "Try it out" button is automatically expanded for all operations. Default: true.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUITryItOut(false), // Require users to click "Try it out"
)
func WithUIValidator ¶
WithUIValidator sets the OpenAPI specification validator URL.
Swagger UI can validate your OpenAPI spec against a validator service. Options:
- ValidatorLocal ("local"): Validate locally using embedded meta-schema (recommended) No external calls, fast, private, works offline
- ValidatorNone ("none") or "": Disable validation
- URL string: Use an external validator service (e.g., "https://validator.swagger.io/validator")
Default: "" (no validation)
Example:
// Use local validation (recommended)
openapi.WithSwaggerUI("/docs",
openapi.WithUIValidator(openapi.ValidatorLocal),
)
// Use external validator
openapi.WithSwaggerUI("/docs",
openapi.WithUIValidator("https://validator.swagger.io/validator"),
)
// Disable validation
openapi.WithSwaggerUI("/docs",
openapi.WithUIValidator(openapi.ValidatorNone),
)
func WithUIWithCredentials ¶
WithUIWithCredentials enables or disables credentials in CORS requests.
When enabled, cookies and authorization headers are included in cross-origin requests. Only enable if your API server is configured to accept credentials. Default: false.
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIWithCredentials(true),
)
type Version ¶ added in v0.4.0
type Version string
Version represents an OpenAPI specification version.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package diag provides diagnostic types for OpenAPI spec generation.
|
Package diag provides diagnostic types for OpenAPI spec generation. |
|
Package example provides types and constructors for OpenAPI Example Objects.
|
Package example provides types and constructors for OpenAPI Example Objects. |
|
internal
|
|
|
build
Package build provides OpenAPI specification building from route metadata.
|
Package build provides OpenAPI specification building from route metadata. |
|
export
Package export provides OpenAPI specification export functionality.
|
Package export provides OpenAPI specification export functionality. |
|
metaschema
Package metaschema provides embedded OpenAPI meta-schema JSON files for validating OpenAPI specifications against the official schemas.
|
Package metaschema provides embedded OpenAPI meta-schema JSON files for validating OpenAPI specifications against the official schemas. |
|
model
Package model provides version-agnostic intermediate representation (IR) types for OpenAPI specifications.
|
Package model provides version-agnostic intermediate representation (IR) types for OpenAPI specifications. |
|
schema
Package schema provides schema generation from Go types using reflection.
|
Package schema provides schema generation from Go types using reflection. |
|
Package validate provides OpenAPI specification validation functionality.
|
Package validate provides OpenAPI specification validation functionality. |