OpenAPI Package
API reference for rivaas.dev/openapi - Automatic OpenAPI specification generation
This is the API reference for the rivaas.dev/openapi package. For learning-focused documentation, see the OpenAPI Guide.
Package Overview
The openapi package provides automatic OpenAPI 3.0.4 and 3.1.2 specification generation from Go code using struct tags and reflection.
Core Features
- Automatic OpenAPI specification generation from Go code
- Support for OpenAPI 3.0.4 and 3.1.2 specifications
- Type-safe version selection with
V30x and V31x constants - Fluent HTTP method constructors (GET, POST, PUT, etc.)
- Automatic parameter discovery from struct tags
- Schema generation from Go types
- Built-in validation against official meta-schemas
- Type-safe warning diagnostics via
diag package - Swagger UI configuration support
Architecture
The package is organized into two main components:
Main Package (rivaas.dev/openapi)
Core specification generation including:
API struct - Configuration containerNew() / MustNew() - API initialization- HTTP method constructors -
GET(), POST(), PUT(), etc. - Operation options -
WithRequest(), WithResponse(), WithSecurity(), etc. Generate() - Specification generation
Sub-package (rivaas.dev/openapi/diag)
Type-safe warning diagnostics:
Warning interface - Individual warningWarnings type - Warning collectionWarningCode type - Type-safe warning codesWarningCategory type - Warning categories
Validator (rivaas.dev/openapi/validate)
Standalone specification validator:
Validator type - Validates OpenAPI specificationsValidate() - Validate against specific versionValidateAuto() - Auto-detect version and validate
Quick API Index
API Creation
api, err := openapi.New(options...) // With error handling
api := openapi.MustNew(options...) // Panics on error
Specification Generation
result, err := api.Generate(ctx context.Context, operations...)
HTTP Method Constructors
openapi.GET(path, ...opts) Operation
openapi.POST(path, ...opts) Operation
openapi.PUT(path, ...opts) Operation
openapi.PATCH(path, ...opts) Operation
openapi.DELETE(path, ...opts) Operation
openapi.HEAD(path, ...opts) Operation
openapi.OPTIONS(path, ...opts) Operation
openapi.TRACE(path, ...opts) Operation
Result Access
result.JSON // OpenAPI spec as JSON bytes
result.YAML // OpenAPI spec as YAML bytes
result.Warnings // Generation warnings
Reference Pages
Core types, HTTP method constructors, and generation API.
View →
API-level configuration for info, servers, and security.
View →
Operation-level configuration for endpoints.
View →
Customize the Swagger UI interface.
View →
Warning system and diagnostic codes.
View →
Common issues and solutions.
View →
Step-by-step tutorials and examples.
View →
Type Reference
API
type API struct {
// contains filtered or unexported fields
}
Main API configuration container. Created via New() or MustNew() with functional options.
Operation
type Operation struct {
// contains filtered or unexported fields
}
Represents an HTTP operation with method, path, and metadata. Created via HTTP method constructors.
Result
type Result struct {
JSON []byte // OpenAPI spec as JSON
YAML []byte // OpenAPI spec as YAML
Warnings Warnings // Generation warnings
}
Result of specification generation containing the spec in multiple formats and any warnings.
Version
type Version int
const (
V30x Version = iota // OpenAPI 3.0.x (generates 3.0.4)
V31x // OpenAPI 3.1.x (generates 3.1.2)
)
Type-safe OpenAPI version selection.
Option
type Option func(*API) error
Functional option for API configuration.
OperationOption
type OperationOption func(*Operation) error
Functional option for operation configuration.
Common Patterns
Basic Generation
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
)
result, err := api.Generate(context.Background(),
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
),
)
With Security
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
)
result, err := api.Generate(context.Background(),
openapi.GET("/users/:id",
openapi.WithSecurity("bearerAuth"),
openapi.WithResponse(200, User{}),
),
)
With Validation
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithValidation(true),
)
result, err := api.Generate(context.Background(), operations...)
// Fails if spec is invalid
With Diagnostics
import "rivaas.dev/openapi/diag"
result, err := api.Generate(context.Background(), operations...)
if err != nil {
log.Fatal(err)
}
if result.Warnings.Has(diag.WarnDownlevelInfoSummary) {
log.Warn("info.summary was dropped")
}
Thread Safety
The API type is safe for concurrent use:
- Multiple goroutines can call
Generate() simultaneously - Configuration is immutable after creation
Not thread-safe:
- Modifying API configuration during initialization
- Schema generation: First use per type ~500ns (reflection), subsequent uses ~50ns (cached)
- Validation: Adds 10-20ms on first validation (schema compilation), 1-5ms subsequent
- Generation: Depends on operation count and complexity
Version Compatibility
The package follows semantic versioning. The API is stable for the v1 series.
Minimum Go version: 1.25
Next Steps
For learning-focused guides, see the OpenAPI Guide.
1 - API Reference
Complete API reference for types, functions, and methods
Complete reference for all types, functions, and methods in the openapi package.
Key Types
API
type API struct {
// contains filtered or unexported fields
}
Main API configuration container. Holds the OpenAPI specification metadata and configuration.
Created by:
New(...Option) (*API, error) - With error handling.MustNew(...Option) *API - Panics on error.
Methods:
Generate(ctx context.Context, ...Operation) (*Result, error) - Generate OpenAPI specification.Version() string - Get target OpenAPI version like “3.0.4” or “3.1.2”.
Operation
type Operation struct {
// contains filtered or unexported fields
}
Represents an HTTP operation with method, path, and configuration.
Created by HTTP method constructors:
GET(path string, ...OperationOption) OperationPOST(path string, ...OperationOption) OperationPUT(path string, ...OperationOption) OperationPATCH(path string, ...OperationOption) OperationDELETE(path string, ...OperationOption) OperationHEAD(path string, ...OperationOption) OperationOPTIONS(path string, ...OperationOption) OperationTRACE(path string, ...OperationOption) Operation
Result
type Result struct {
JSON []byte
YAML []byte
Warnings Warnings
}
Result of specification generation.
Fields:
JSON - OpenAPI specification as JSON bytes.YAML - OpenAPI specification as YAML bytes.Warnings - Collection of generation warnings. Check Diagnostics for details.
Version
type Version int
const (
V30x Version = iota // OpenAPI 3.0.x (generates 3.0.4)
V31x // OpenAPI 3.1.x (generates 3.1.2)
)
Type-safe OpenAPI version selection. Use with WithVersion() option.
Constants:
V30x - Target OpenAPI 3.0.x family. Generates 3.0.4 specification.V31x - Target OpenAPI 3.1.x family. Generates 3.1.2 specification.
Option
type Option func(*API) error
Functional option for configuring the API. See Options for all available options.
OperationOption
type OperationOption func(*Operation) error
Functional option for configuring operations. See Operation Options for all available options.
Functions
New
func New(opts ...Option) (*API, error)
Creates a new API configuration with error handling.
Parameters:
opts - Variable number of Option functions
Returns:
*API - Configured API instanceerror - Configuration error if any
Example:
api, err := openapi.New(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithServer("http://localhost:8080", "Development"),
)
if err != nil {
log.Fatal(err)
}
MustNew
func MustNew(opts ...Option) *API
Creates a new API configuration. Panics if configuration fails.
Parameters:
opts - Variable number of Option functions
Returns:
*API - Configured API instance
Panics:
Example:
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithServer("http://localhost:8080", "Development"),
)
HTTP Method Constructors
GET
func GET(path string, opts ...OperationOption) Operation
Creates a GET operation.
Parameters:
path - URL path (use :param syntax for path parameters)opts - Variable number of OperationOption functions
Returns:
Operation - Configured operation
Example:
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
)
POST
func POST(path string, opts ...OperationOption) Operation
Creates a POST operation.
Parameters:
path - URL pathopts - Variable number of OperationOption functions
Returns:
Operation - Configured operation
Example:
openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
openapi.WithResponse(201, User{}),
)
PUT
func PUT(path string, opts ...OperationOption) Operation
Creates a PUT operation.
PATCH
func PATCH(path string, opts ...OperationOption) Operation
Creates a PATCH operation.
DELETE
func DELETE(path string, opts ...OperationOption) Operation
Creates a DELETE operation.
Example:
openapi.DELETE("/users/:id",
openapi.WithSummary("Delete user"),
openapi.WithResponse(204, nil),
)
HEAD
func HEAD(path string, opts ...OperationOption) Operation
Creates a HEAD operation.
OPTIONS
func OPTIONS(path string, opts ...OperationOption) Operation
Creates an OPTIONS operation.
TRACE
func TRACE(path string, opts ...OperationOption) Operation
Creates a TRACE operation.
Methods
API.Generate
func (api *API) Generate(ctx context.Context, operations ...Operation) (*Result, error)
Generates an OpenAPI specification from the configured API and operations.
Parameters:
ctx - Context for cancellationoperations - Variable number of Operation instances
Returns:
*Result - Generation result with JSON, YAML, and warningserror - Generation or validation error if any
Errors:
- Returns error if context is nil
- Returns error if generation fails
- Returns error if validation is enabled and spec is invalid
Example:
result, err := api.Generate(context.Background(),
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
),
openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
openapi.WithResponse(201, User{}),
),
)
if err != nil {
log.Fatal(err)
}
// Use result.JSON or result.YAML
fmt.Println(string(result.JSON))
API.Version
func (api *API) Version() string
Returns the target OpenAPI version as a string.
Returns:
string - Version string (“3.0.4” or “3.1.2”)
Example:
api := openapi.MustNew(
openapi.WithTitle("API", "1.0.0"),
openapi.WithVersion(openapi.V31x),
)
fmt.Println(api.Version()) // "3.1.2"
Type Aliases and Constants
Parameter Locations
const (
InHeader ParameterLocation = "header"
InQuery ParameterLocation = "query"
InCookie ParameterLocation = "cookie"
)
Used with WithAPIKey() to specify where the API key is located.
OAuth2 Flow Types
const (
FlowAuthorizationCode OAuthFlowType = "authorizationCode"
FlowImplicit OAuthFlowType = "implicit"
FlowPassword OAuthFlowType = "password"
FlowClientCredentials OAuthFlowType = "clientCredentials"
)
Used with WithOAuth2() to specify the OAuth2 flow type.
Swagger UI Constants
// Document expansion
const (
DocExpansionList DocExpansion = "list"
DocExpansionFull DocExpansion = "full"
DocExpansionNone DocExpansion = "none"
)
// Model rendering
const (
ModelRenderingExample ModelRendering = "example"
ModelRenderingModel ModelRendering = "model"
)
// Operations sorting
const (
OperationsSorterAlpha OperationsSorter = "alpha"
OperationsSorterMethod OperationsSorter = "method"
)
// Tags sorting
const (
TagsSorterAlpha TagsSorter = "alpha"
)
// Validators (untyped string constants)
const (
ValidatorLocal = "local" // Use embedded meta-schema validation
ValidatorNone = "none" // Disable validation
)
// Syntax themes
const (
SyntaxThemeAgate SyntaxTheme = "agate"
SyntaxThemeArta SyntaxTheme = "arta"
SyntaxThemeMonokai SyntaxTheme = "monokai"
SyntaxThemeNord SyntaxTheme = "nord"
SyntaxThemeObsidian SyntaxTheme = "obsidian"
SyntaxThemeTomorrowNight SyntaxTheme = "tomorrow-night"
SyntaxThemeIdea SyntaxTheme = "idea"
)
// Request snippet languages
const (
SnippetCurlBash RequestSnippetLanguage = "curl_bash"
SnippetCurlPowerShell RequestSnippetLanguage = "curl_powershell"
SnippetCurlCmd RequestSnippetLanguage = "curl_cmd"
)
See Swagger UI Options for usage.
Next Steps
2 - API Options
Complete reference for API-level configuration options
Complete reference for all API-level configuration options (functions passed to New() or MustNew()).
Info Options
WithTitle
func WithTitle(title, version string) Option
Sets the API title and version. Required.
Parameters:
title - API title.version - API version like “1.0.0”.
Example:
openapi.WithTitle("My API", "1.0.0")
WithInfoDescription
func WithInfoDescription(description string) Option
Sets the API description.
Example:
openapi.WithInfoDescription("Comprehensive API for managing users and resources")
WithInfoSummary
func WithInfoSummary(summary string) Option
Sets a short summary for the API. OpenAPI 3.1 only. Generates warning if used with 3.0 target.
Example:
openapi.WithInfoSummary("User Management API")
WithTermsOfService
func WithTermsOfService(url string) Option
Sets the terms of service URL.
Example:
openapi.WithTermsOfService("https://example.com/terms")
func WithContact(name, url, email string) Option
Sets contact information.
Parameters:
name - Contact nameurl - Contact URLemail - Contact email
Example:
openapi.WithContact("API Support", "https://example.com/support", "support@example.com")
WithLicense
func WithLicense(name, url string) Option
Sets license information.
Parameters:
name - License nameurl - License URL
Example:
openapi.WithLicense("Apache 2.0", "https://www.apache.org/licenses/LICENSE-2.0.html")
WithLicenseIdentifier
func WithLicenseIdentifier(name, identifier string) Option
Sets license with SPDX identifier. OpenAPI 3.1 only.
Parameters:
name - License nameidentifier - SPDX license identifier
Example:
openapi.WithLicenseIdentifier("Apache 2.0", "Apache-2.0")
WithInfoExtension
func WithInfoExtension(key string, value any) Option
Adds a custom extension to the info object.
Parameters:
key - Extension key (must start with x-)value - Extension value
Example:
openapi.WithInfoExtension("x-api-id", "user-service")
Version Options
WithVersion
func WithVersion(version Version) Option
Sets the target OpenAPI version. Default is V30x.
Parameters:
version - Either V30x or V31x
Example:
openapi.WithVersion(openapi.V31x)
Server Options
WithServer
func WithServer(url, description string) Option
Adds a server configuration.
Parameters:
url - Server URLdescription - Server description
Example:
openapi.WithServer("https://api.example.com", "Production")
openapi.WithServer("http://localhost:8080", "Development")
WithServerVariable
func WithServerVariable(name, defaultValue string, enumValues []string, description string) Option
Adds a server variable for URL templating.
Parameters:
name - Variable namedefaultValue - Default valueenumValues - Allowed valuesdescription - Variable description
Example:
openapi.WithServer("https://{environment}.example.com", "Environment-based"),
openapi.WithServerVariable("environment", "api",
[]string{"api", "staging", "dev"},
"Environment to use",
)
Security Scheme Options
WithBearerAuth
func WithBearerAuth(name, description string) Option
Adds Bearer (JWT) authentication scheme.
Parameters:
name - Security scheme name (used in WithSecurity())description - Scheme description
Example:
openapi.WithBearerAuth("bearerAuth", "JWT authentication")
WithAPIKey
func WithAPIKey(name, paramName string, location ParameterLocation, description string) Option
Adds API key authentication scheme.
Parameters:
name - Security scheme nameparamName - Parameter name (e.g., “X-API-Key”, “api_key”)location - Where the key is located: InHeader, InQuery, or InCookiedescription - Scheme description
Example:
openapi.WithAPIKey("apiKey", "X-API-Key", openapi.InHeader, "API key for authentication")
WithOAuth2
func WithOAuth2(name, description string, flows ...OAuth2Flow) Option
Adds OAuth2 authentication scheme.
Parameters:
name - Security scheme namedescription - Scheme descriptionflows - OAuth2 flow configurations
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",
},
},
)
WithOpenIDConnect
func WithOpenIDConnect(name, openIDConnectURL, description string) Option
Adds OpenID Connect authentication scheme.
Parameters:
name - Security scheme nameopenIDConnectURL - OpenID Connect discovery URLdescription - Scheme description
Example:
openapi.WithOpenIDConnect("openId", "https://example.com/.well-known/openid-configuration", "OpenID Connect")
WithDefaultSecurity
func WithDefaultSecurity(scheme string, scopes ...string) Option
Sets default security requirement at API level (applies to all operations unless overridden).
Parameters:
scheme - Security scheme namescopes - Optional OAuth2 scopes
Example:
openapi.WithDefaultSecurity("bearerAuth")
openapi.WithDefaultSecurity("oauth2", "read", "write")
Tag Options
WithTag
func WithTag(name, description string) Option
Adds a tag for organizing operations.
Parameters:
name - Tag namedescription - Tag description
Example:
openapi.WithTag("users", "User management operations")
openapi.WithTag("posts", "Post management operations")
External Documentation
WithExternalDocs
func WithExternalDocs(url, description string) Option
Links to external documentation.
Parameters:
url - Documentation URLdescription - Documentation description
Example:
openapi.WithExternalDocs("https://docs.example.com", "Full API Documentation")
Validation Options
WithValidation
func WithValidation(enabled bool) Option
Enables or disables specification validation. Default is false.
Parameters:
enabled - Whether to validate generated specs
Example:
openapi.WithValidation(true) // Enable validation
WithStrictDownlevel
func WithStrictDownlevel(enabled bool) Option
Enables strict downlevel mode. When enabled, using 3.1 features with a 3.0 target causes errors instead of warnings. Default is false.
Parameters:
enabled - Whether to error on downlevel issues
Example:
openapi.WithStrictDownlevel(true) // Error on 3.1 features with 3.0 target
WithSpecPath
func WithSpecPath(path string) Option
Sets the path where the OpenAPI specification will be served.
Parameters:
path - URL path for the spec (e.g., “/openapi.json”)
Example:
openapi.WithSpecPath("/api/openapi.json")
Swagger UI Options
WithSwaggerUI
func WithSwaggerUI(path string, opts ...UIOption) Option
Configures Swagger UI at the specified path.
Parameters:
path - URL path where Swagger UI is servedopts - Swagger UI configuration options (see Swagger UI Options)
Example:
openapi.WithSwaggerUI("/docs",
openapi.WithUIExpansion(openapi.DocExpansionList),
openapi.WithUITryItOut(true),
)
WithoutSwaggerUI
func WithoutSwaggerUI() Option
Disables Swagger UI.
Example:
openapi.WithoutSwaggerUI()
Extension Options
WithExtension
func WithExtension(key string, value interface{}) Option
Adds a custom x-* extension to the root of the specification.
Parameters:
key - Extension key (must start with x-)value - Extension value (any JSON-serializable type)
Example:
openapi.WithExtension("x-api-version", "v2")
openapi.WithExtension("x-custom-config", map[string]interface{}{
"feature": "enabled",
"rate-limit": 100,
})
Next Steps
3 - Operation Options
Complete reference for operation-level configuration options
Complete reference for all operation-level configuration options (functions passed to HTTP method constructors).
WithSummary
func WithSummary(summary string) OperationOption
Sets the operation summary (short description).
Example:
openapi.WithSummary("Get user by ID")
WithDescription
func WithDescription(description string) OperationOption
Sets the operation description (detailed explanation).
Example:
openapi.WithDescription("Retrieves a user by their unique identifier from the database")
WithOperationID
func WithOperationID(operationID string) OperationOption
Sets a custom operation ID. By default, operation IDs are auto-generated from method and path.
Example:
openapi.WithOperationID("getUserById")
Request and Response Options
WithRequest
func WithRequest(requestType interface{}, examples ...interface{}) OperationOption
Sets the request body type with optional examples.
Parameters:
requestType - Go type to convert to schemaexamples - Optional example instances
Example:
exampleUser := CreateUserRequest{Name: "John", Email: "john@example.com"}
openapi.WithRequest(CreateUserRequest{}, exampleUser)
WithResponse
func WithResponse(statusCode int, responseType interface{}, examples ...interface{}) OperationOption
Adds a response type for a specific status code.
Parameters:
statusCode - HTTP status coderesponseType - Go type to convert to schema (use nil for no body)examples - Optional example instances
Example:
openapi.WithResponse(200, User{})
openapi.WithResponse(204, nil) // No response body
openapi.WithResponse(404, ErrorResponse{})
Organization Options
func WithTags(tags ...string) OperationOption
Adds tags to the operation for organization.
Parameters:
Example:
openapi.WithTags("users")
openapi.WithTags("users", "admin")
Security Options
WithSecurity
func WithSecurity(scheme string, scopes ...string) OperationOption
Adds a security requirement to the operation.
Parameters:
scheme - Security scheme name (defined with WithBearerAuth, WithAPIKey, etc.)scopes - Optional OAuth2 scopes
Example:
openapi.WithSecurity("bearerAuth")
openapi.WithSecurity("oauth2", "read", "write")
Multiple calls create alternative security requirements (OR logic):
openapi.GET("/users/:id",
openapi.WithSecurity("bearerAuth"), // Can use bearer auth
openapi.WithSecurity("apiKey"), // OR can use API key
openapi.WithResponse(200, User{}),
)
Content Type Options
WithConsumes
func WithConsumes(contentTypes ...string) OperationOption
Sets accepted content types for the request.
Parameters:
contentTypes - MIME types
Example:
openapi.WithConsumes("application/json", "application/xml")
WithProduces
func WithProduces(contentTypes ...string) OperationOption
Sets returned content types for the response.
Parameters:
contentTypes - MIME types
Example:
openapi.WithProduces("application/json", "application/xml")
Deprecation
WithDeprecated
func WithDeprecated() OperationOption
Marks the operation as deprecated.
Example:
openapi.GET("/users/legacy",
openapi.WithSummary("Legacy user list"),
openapi.WithDeprecated(),
openapi.WithResponse(200, []User{}),
)
Extension Options
WithOperationExtension
func WithOperationExtension(key string, value interface{}) OperationOption
Adds a custom x-* extension to the operation.
Parameters:
key - Extension key (must start with x-)value - Extension value (any JSON-serializable type)
Example:
openapi.WithOperationExtension("x-rate-limit", 100)
openapi.WithOperationExtension("x-cache-ttl", 300)
Composable Options
WithOptions
func WithOptions(opts ...OperationOption) OperationOption
Combines multiple operation options into a single reusable option.
Parameters:
opts - Operation options to combine
Example:
CommonErrors := openapi.WithOptions(
openapi.WithResponse(400, ErrorResponse{}),
openapi.WithResponse(500, ErrorResponse{}),
)
UserEndpoint := openapi.WithOptions(
openapi.WithTags("users"),
openapi.WithSecurity("bearerAuth"),
CommonErrors,
)
// Use in operations
openapi.GET("/users/:id",
UserEndpoint,
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
)
Option Summary Table
| Option | Description |
|---|
WithSummary(s) | Set operation summary |
WithDescription(s) | Set operation description |
WithOperationID(id) | Set custom operation ID |
WithRequest(type, examples...) | Set request body type |
WithResponse(status, type, examples...) | Set response type for status code |
WithTags(tags...) | Add tags to operation |
WithSecurity(scheme, scopes...) | Add security requirement |
WithDeprecated() | Mark operation as deprecated |
WithConsumes(types...) | Set accepted content types |
WithProduces(types...) | Set returned content types |
WithOperationExtension(key, value) | Add operation extension |
WithOptions(opts...) | Combine options into reusable set |
Next Steps
4 - Swagger UI Options
Complete reference for Swagger UI configuration options
Complete reference for all Swagger UI configuration options (functions passed to WithSwaggerUI()).
Display Options
WithUIExpansion
func WithUIExpansion(expansion DocExpansion) UIOption
Controls initial document expansion.
Parameters:
expansion - DocExpansionList, DocExpansionFull, or DocExpansionNone
Values:
DocExpansionList - Show endpoints, hide details (default)DocExpansionFull - Show endpoints and detailsDocExpansionNone - Hide everything
Example:
openapi.WithUIExpansion(openapi.DocExpansionFull)
WithUIDefaultModelRendering
func WithUIDefaultModelRendering(rendering ModelRendering) UIOption
Controls how models/schemas are rendered.
Parameters:
rendering - ModelRenderingExample or ModelRenderingModel
Example:
openapi.WithUIDefaultModelRendering(openapi.ModelRenderingExample)
WithUIModelExpandDepth
func WithUIModelExpandDepth(depth int) UIOption
Controls how deeply a single model is expanded.
Parameters:
depth - Expansion depth (-1 to disable, 1 for shallow, higher for deeper)
Example:
openapi.WithUIModelExpandDepth(2)
WithUIModelsExpandDepth
func WithUIModelsExpandDepth(depth int) UIOption
Controls how deeply the models section is expanded.
Example:
openapi.WithUIModelsExpandDepth(1)
WithUIDisplayOperationID
func WithUIDisplayOperationID(display bool) UIOption
Shows operation IDs alongside summaries.
Example:
openapi.WithUIDisplayOperationID(true)
Try It Out Options
WithUITryItOut
func WithUITryItOut(enabled bool) UIOption
Enables “Try it out” functionality.
Example:
openapi.WithUITryItOut(true)
WithUIRequestSnippets
func WithUIRequestSnippets(enabled bool, languages ...RequestSnippetLanguage) UIOption
Shows code snippets for making requests.
Parameters:
enabled - Whether to show snippetslanguages - Snippet languages to show
Languages:
SnippetCurlBash - curl for bash/sh shellsSnippetCurlPowerShell - curl for PowerShellSnippetCurlCmd - curl for Windows CMD
Example:
openapi.WithUIRequestSnippets(true,
openapi.SnippetCurlBash,
openapi.SnippetCurlPowerShell,
openapi.SnippetCurlCmd,
)
WithUIRequestSnippetsExpanded
func WithUIRequestSnippetsExpanded(expanded bool) UIOption
Expands request snippets by default.
Example:
openapi.WithUIRequestSnippetsExpanded(true)
WithUIDisplayRequestDuration
func WithUIDisplayRequestDuration(display bool) UIOption
Shows how long requests take.
Example:
openapi.WithUIDisplayRequestDuration(true)
Filtering and Sorting Options
WithUIFilter
func WithUIFilter(enabled bool) UIOption
Enables filter/search box.
Example:
openapi.WithUIFilter(true)
func WithUIMaxDisplayedTags(max int) UIOption
Limits the number of tags displayed.
Example:
openapi.WithUIMaxDisplayedTags(10)
WithUIOperationsSorter
func WithUIOperationsSorter(sorter OperationsSorter) UIOption
Sets operation sorting method.
Parameters:
sorter - OperationsSorterAlpha or OperationsSorterMethod
Example:
openapi.WithUIOperationsSorter(openapi.OperationsSorterAlpha)
func WithUITagsSorter(sorter TagsSorter) UIOption
Sets tag sorting method.
Parameters:
Example:
openapi.WithUITagsSorter(openapi.TagsSorterAlpha)
Syntax Highlighting Options
WithUISyntaxHighlight
func WithUISyntaxHighlight(enabled bool) UIOption
Enables syntax highlighting.
Example:
openapi.WithUISyntaxHighlight(true)
WithUISyntaxTheme
func WithUISyntaxTheme(theme SyntaxTheme) UIOption
Sets syntax highlighting theme.
Available Themes:
SyntaxThemeAgate - Dark theme with blue accentsSyntaxThemeArta - Dark theme with orange accentsSyntaxThemeMonokai - Dark theme with vibrant colorsSyntaxThemeNord - Dark theme with cool blue tonesSyntaxThemeObsidian - Dark theme with green accentsSyntaxThemeTomorrowNight - Dark theme with muted colorsSyntaxThemeIdea - Light theme similar to IntelliJ IDEA
Example:
openapi.WithUISyntaxTheme(openapi.SyntaxThemeMonokai)
Authentication Options
WithUIPersistAuth
func WithUIPersistAuth(persist bool) UIOption
Persists authentication across browser refreshes.
Example:
openapi.WithUIPersistAuth(true)
WithUIWithCredentials
func WithUIWithCredentials(withCredentials bool) UIOption
Includes credentials in requests.
Example:
openapi.WithUIWithCredentials(true)
Additional Options
WithUIDeepLinking
func WithUIDeepLinking(enabled bool) UIOption
Enables deep linking for tags and operations.
Example:
openapi.WithUIDeepLinking(true)
WithUIShowExtensions
func WithUIShowExtensions(show bool) UIOption
Shows vendor extensions (x-*) in the UI.
Example:
openapi.WithUIShowExtensions(true)
WithUIShowCommonExtensions
func WithUIShowCommonExtensions(show bool) UIOption
Shows common extensions in the UI.
Example:
openapi.WithUIShowCommonExtensions(true)
WithUISupportedMethods
func WithUISupportedMethods(methods ...HTTPMethod) UIOption
Configures which HTTP methods are supported for “Try it out”.
Parameters:
methods - HTTP method constants (MethodGet, MethodPost, MethodPut, etc.)
Example:
openapi.WithUISupportedMethods(
openapi.MethodGet,
openapi.MethodPost,
openapi.MethodPut,
openapi.MethodDelete,
)
Validation Options
WithUIValidator
func WithUIValidator(url string) UIOption
Sets specification validator.
Parameters:
url - ValidatorLocal, ValidatorNone, or custom validator URL
Example:
openapi.WithUIValidator(openapi.ValidatorLocal)
openapi.WithUIValidator("https://validator.swagger.io/validator")
openapi.WithUIValidator(openapi.ValidatorNone)
Complete Example
openapi.WithSwaggerUI("/docs",
// Display
openapi.WithUIExpansion(openapi.DocExpansionList),
openapi.WithUIModelExpandDepth(1),
openapi.WithUIDisplayOperationID(true),
// Try it out
openapi.WithUITryItOut(true),
openapi.WithUIRequestSnippets(true,
openapi.SnippetCurlBash,
openapi.SnippetCurlPowerShell,
openapi.SnippetCurlCmd,
),
openapi.WithUIDisplayRequestDuration(true),
// Filtering/Sorting
openapi.WithUIFilter(true),
openapi.WithUIOperationsSorter(openapi.OperationsSorterAlpha),
// Syntax
openapi.WithUISyntaxHighlight(true),
openapi.WithUISyntaxTheme(openapi.SyntaxThemeMonokai),
// Auth
openapi.WithUIPersistAuth(true),
// Validation
openapi.WithUIValidator(openapi.ValidatorLocal),
)
Next Steps
5 - Diagnostics
Warning system reference with codes and categories
Complete reference for the warning diagnostics system in rivaas.dev/openapi/diag.
Package Import
import "rivaas.dev/openapi/diag"
Warning Interface
type Warning interface {
Code() WarningCode
Message() string
Path() string
Category() WarningCategory
}
Individual warning with diagnostic information.
Methods:
Code() - Returns type-safe warning codeMessage() - Returns human-readable messagePath() - Returns location in spec (e.g., “info.summary”)Category() - Returns warning category
Warnings Collection
Collection of warnings with helper methods.
Has
func (w Warnings) Has(code WarningCode) bool
Checks if collection contains a specific warning code.
Example:
if result.Warnings.Has(diag.WarnDownlevelInfoSummary) {
log.Warn("info.summary was dropped")
}
HasAny
func (w Warnings) HasAny(codes ...WarningCode) bool
Checks if collection contains any of the specified warning codes.
Example:
if result.Warnings.HasAny(
diag.WarnDownlevelMutualTLS,
diag.WarnDownlevelWebhooks,
) {
log.Warn("Some 3.1 security features were dropped")
}
Filter
func (w Warnings) Filter(code WarningCode) Warnings
Returns warnings matching the specified code.
Example:
licenseWarnings := result.Warnings.Filter(diag.WarnDownlevelLicenseIdentifier)
FilterCategory
func (w Warnings) FilterCategory(category WarningCategory) Warnings
Returns warnings in the specified category.
Example:
downlevelWarnings := result.Warnings.FilterCategory(diag.CategoryDownlevel)
Exclude
func (w Warnings) Exclude(codes ...WarningCode) Warnings
Returns warnings excluding the specified codes.
Example:
expected := []diag.WarningCode{
diag.WarnDownlevelInfoSummary,
}
unexpected := result.Warnings.Exclude(expected...)
Warning Codes
WarningCode Type
Type-safe warning code constant.
Downlevel Warning Codes
Warnings generated when using 3.1 features with a 3.0 target:
| Constant | Code Value | Description |
|---|
WarnDownlevelWebhooks | DOWNLEVEL_WEBHOOKS | Webhooks dropped (3.0 doesn’t support them) |
WarnDownlevelInfoSummary | DOWNLEVEL_INFO_SUMMARY | info.summary dropped (3.0 doesn’t support it) |
WarnDownlevelLicenseIdentifier | DOWNLEVEL_LICENSE_IDENTIFIER | license.identifier dropped |
WarnDownlevelMutualTLS | DOWNLEVEL_MUTUAL_TLS | mutualTLS security scheme dropped |
WarnDownlevelConstToEnum | DOWNLEVEL_CONST_TO_ENUM | JSON Schema const converted to enum |
WarnDownlevelConstToEnumConflict | DOWNLEVEL_CONST_TO_ENUM_CONFLICT | const conflicted with existing enum |
WarnDownlevelPathItems | DOWNLEVEL_PATH_ITEMS | $ref in pathItems was expanded |
WarnDownlevelPatternProperties | DOWNLEVEL_PATTERN_PROPERTIES | patternProperties dropped |
WarnDownlevelUnevaluatedProperties | DOWNLEVEL_UNEVALUATED_PROPERTIES | unevaluatedProperties dropped |
WarnDownlevelContentEncoding | DOWNLEVEL_CONTENT_ENCODING | contentEncoding dropped |
WarnDownlevelContentMediaType | DOWNLEVEL_CONTENT_MEDIA_TYPE | contentMediaType dropped |
WarnDownlevelMultipleExamples | DOWNLEVEL_MULTIPLE_EXAMPLES | Multiple examples collapsed to one |
const (
WarnDownlevelWebhooks WarningCode = "DOWNLEVEL_WEBHOOKS"
WarnDownlevelInfoSummary WarningCode = "DOWNLEVEL_INFO_SUMMARY"
WarnDownlevelLicenseIdentifier WarningCode = "DOWNLEVEL_LICENSE_IDENTIFIER"
WarnDownlevelMutualTLS WarningCode = "DOWNLEVEL_MUTUAL_TLS"
WarnDownlevelConstToEnum WarningCode = "DOWNLEVEL_CONST_TO_ENUM"
WarnDownlevelConstToEnumConflict WarningCode = "DOWNLEVEL_CONST_TO_ENUM_CONFLICT"
WarnDownlevelPathItems WarningCode = "DOWNLEVEL_PATH_ITEMS"
WarnDownlevelPatternProperties WarningCode = "DOWNLEVEL_PATTERN_PROPERTIES"
WarnDownlevelUnevaluatedProperties WarningCode = "DOWNLEVEL_UNEVALUATED_PROPERTIES"
WarnDownlevelContentEncoding WarningCode = "DOWNLEVEL_CONTENT_ENCODING"
WarnDownlevelContentMediaType WarningCode = "DOWNLEVEL_CONTENT_MEDIA_TYPE"
WarnDownlevelMultipleExamples WarningCode = "DOWNLEVEL_MULTIPLE_EXAMPLES"
)
Deprecation Warning Codes
Warnings for deprecated feature usage:
| Constant | Code Value | Description |
|---|
WarnDeprecationExampleSingular | DEPRECATION_EXAMPLE_SINGULAR | Using deprecated singular example field |
const (
WarnDeprecationExampleSingular WarningCode = "DEPRECATION_EXAMPLE_SINGULAR"
)
Warning Categories
WarningCategory Type
type WarningCategory string
Category grouping for warnings.
Category Constants
| Category | Description |
|---|
CategoryDownlevel | 3.1 to 3.0 conversion feature losses (spec is still valid) |
CategoryDeprecation | Deprecated feature usage (feature still works but is discouraged) |
CategoryUnknown | Unrecognized warning codes |
const (
CategoryDownlevel WarningCategory = "downlevel"
CategoryDeprecation WarningCategory = "deprecation"
CategoryUnknown WarningCategory = "unknown"
)
Usage Examples
Check for Specific Warning
import "rivaas.dev/openapi/diag"
result, err := api.Generate(context.Background(), ops...)
if err != nil {
log.Fatal(err)
}
if result.Warnings.Has(diag.WarnDownlevelInfoSummary) {
log.Warn("info.summary was dropped (3.1 feature with 3.0 target)")
}
Filter by Category
downlevelWarnings := result.Warnings.FilterCategory(diag.CategoryDownlevel)
if len(downlevelWarnings) > 0 {
fmt.Printf("Downlevel warnings: %d\n", len(downlevelWarnings))
for _, warn := range downlevelWarnings {
fmt.Printf(" [%s] %s at %s\n",
warn.Code(),
warn.Message(),
warn.Path(),
)
}
}
Check for Unexpected Warnings
expected := []diag.WarningCode{
diag.WarnDownlevelInfoSummary,
diag.WarnDownlevelLicenseIdentifier,
}
unexpected := result.Warnings.Exclude(expected...)
if len(unexpected) > 0 {
log.Fatalf("Unexpected warnings: %d", len(unexpected))
}
Iterate All Warnings
for _, warn := range result.Warnings {
fmt.Printf("[%s] %s\n", warn.Code(), warn.Message())
fmt.Printf(" Location: %s\n", warn.Path())
fmt.Printf(" Category: %s\n", warn.Category())
}
Complete Example
package main
import (
"context"
"fmt"
"log"
"rivaas.dev/openapi"
"rivaas.dev/openapi/diag"
)
func main() {
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithVersion(openapi.V30x),
openapi.WithInfoSummary("API Summary"), // 3.1 feature
)
result, err := api.Generate(context.Background(), operations...)
if err != nil {
log.Fatal(err)
}
// Handle specific warnings
if result.Warnings.Has(diag.WarnDownlevelInfoSummary) {
fmt.Println("Note: info.summary was dropped")
}
// Filter by category
downlevelWarnings := result.Warnings.FilterCategory(diag.CategoryDownlevel)
fmt.Printf("Downlevel warnings: %d\n", len(downlevelWarnings))
// Check for unexpected
expected := []diag.WarningCode{
diag.WarnDownlevelInfoSummary,
}
unexpected := result.Warnings.Exclude(expected...)
if len(unexpected) > 0 {
fmt.Printf("UNEXPECTED warnings: %d\n", len(unexpected))
for _, warn := range unexpected {
fmt.Printf(" [%s] %s\n", warn.Code(), warn.Message())
}
log.Fatal("Unexpected warnings found")
}
fmt.Println("Generation complete")
}
Next Steps
6 - Troubleshooting
Common issues and solutions
Common issues and solutions for the openapi package.
Schema Name Collisions
Problem
Types with the same name in different packages may collide in the generated specification.
Solution
The package automatically uses pkgname.TypeName format for schema names:
// In package "api"
type User struct { ... } // Becomes "api.User"
// In package "models"
type User struct { ... } // Becomes "models.User"
If you need custom schema names, use the openapi struct tag:
type User struct {
ID int `json:"id" openapi:"name=CustomUser"`
Name string `json:"name"`
}
Extension Validation
Problem
Custom extensions are rejected or filtered out.
Solution
Extensions must follow OpenAPI rules:
Valid:
openapi.WithExtension("x-custom", "value")
openapi.WithExtension("x-api-version", "v2")
Invalid:
// Missing x- prefix
openapi.WithExtension("custom", "value") // Error
// Reserved prefix in 3.1.x
openapi.WithExtension("x-oai-custom", "value") // Filtered out in 3.1.x
openapi.WithExtension("x-oas-custom", "value") // Filtered out in 3.1.x
Version Compatibility
Problem
Using OpenAPI 3.1 features with a 3.0 target generates warnings or errors.
Solution
When using OpenAPI 3.0.x target, some 3.1.x features are automatically down-leveled:
| Feature | 3.0 Behavior |
|---|
info.summary | Dropped (warning) |
license.identifier | Dropped (warning) |
const in schemas | Converted to enum with single value |
examples (multiple) | Converted to single example |
webhooks | Dropped (warning) |
mutualTLS security | Dropped (warning) |
Options:
- Accept warnings (default):
api := openapi.MustNew(
openapi.WithVersion(openapi.V30x),
openapi.WithInfoSummary("Summary"), // Generates warning
)
result, err := api.Generate(context.Background(), ops...)
// Check result.Warnings
- Enable strict mode (error on 3.1 features):
api := openapi.MustNew(
openapi.WithVersion(openapi.V30x),
openapi.WithStrictDownlevel(true), // Error on 3.1 features
openapi.WithInfoSummary("Summary"), // Causes error
)
- Use 3.1 target:
api := openapi.MustNew(
openapi.WithVersion(openapi.V31x), // All features available
openapi.WithInfoSummary("Summary"), // No warning
)
Parameters Not Discovered
Problem
Parameters are not appearing in the generated specification.
Solution
Ensure struct tags are correct:
Common Issues:
// Wrong tag name
type Request struct {
ID int `params:"id"` // Should be "path", "query", "header", or "cookie"
}
// Missing tag
type Request struct {
ID int // No tag - won't be discovered
}
// Wrong location
type Request struct {
ID int `query:"id"` // Should be "path" for path parameters
}
Correct:
type Request struct {
// Path parameters
ID int `path:"id" doc:"User ID"`
// Query parameters
Page int `query:"page" doc:"Page number"`
// Header parameters
Auth string `header:"Authorization" doc:"Auth token"`
// Cookie parameters
Session string `cookie:"session_id" doc:"Session ID"`
}
Validation Errors
Problem
Generated specification fails validation.
Solution
Enable validation to get detailed error messages:
api := openapi.MustNew(
openapi.WithTitle("My API", "1.0.0"),
openapi.WithValidation(true), // Enable validation
)
result, err := api.Generate(context.Background(), ops...)
if err != nil {
log.Printf("Validation failed: %v\n", err)
}
Common validation errors:
- Missing required fields:
// Missing version
openapi.MustNew(
openapi.WithTitle("My API", ""), // Version required
)
- Invalid URLs:
// Invalid server URL
openapi.WithServer("not-a-url", "Server")
- Invalid enum values:
type Request struct {
Status string `json:"status" enum:"active"` // Missing comma-separated values
}
Problem
Specification generation is slow.
Solution
Typical performance:
- First generation per type: ~500ns (reflection)
- Subsequent generations: ~50ns (cached)
- Validation overhead: 10-20ms first time, 1-5ms subsequent
Optimization tips:
- Disable validation in production:
api := openapi.MustNew(
openapi.WithTitle("API", "1.0.0"),
openapi.WithValidation(false), // Disable for production
)
- Generate once, cache result:
var cachedSpec []byte
var once sync.Once
func getSpec() []byte {
once.Do(func() {
result, _ := api.Generate(context.Background(), ops...)
cachedSpec = result.JSON
})
return cachedSpec
}
- Pre-generate at build time:
# generate-spec.go
go run generate-spec.go > openapi.json
Schema Generation Issues
Problem
Go types are not converted correctly to OpenAPI schemas.
Solution
Supported types:
type Example struct {
// Primitives
String string `json:"string"`
Int int `json:"int"`
Bool bool `json:"bool"`
Float float64 `json:"float"`
// Pointers (nullable)
Optional *string `json:"optional,omitempty"`
// Slices
Tags []string `json:"tags"`
// Maps
Metadata map[string]string `json:"metadata"`
// Nested structs
Address Address `json:"address"`
// Time
CreatedAt time.Time `json:"created_at"`
}
Unsupported types:
type Unsupported struct {
Channel chan int // Not supported
Func func() // Not supported
Complex complex64 // Not supported
}
Workaround for unsupported types:
Use custom types or JSON marshaling:
type CustomType struct {
data interface{}
}
func (c CustomType) MarshalJSON() ([]byte, error) {
// Custom marshaling logic
}
Context Errors
Problem
Generate() returns “context is nil” error.
Solution
Always provide a valid context:
// Wrong
result, err := api.Generate(nil, ops...) // Error
// Correct
result, err := api.Generate(context.Background(), ops...)
result, err := api.Generate(ctx, ops...) // With existing context
Common FAQ
Q: How do I make a parameter optional?
A: For query/header/cookie parameters, omit validate:"required" tag. For request body fields, use pointer types or omitempty:
type Request struct {
Required string `json:"required" validate:"required"`
Optional *string `json:"optional,omitempty"`
}
Q: How do I add multiple examples?
A: Pass multiple example instances to WithRequest() or WithResponse():
example1 := User{ID: 1, Name: "Alice"}
example2 := User{ID: 2, Name: "Bob"}
openapi.WithResponse(200, User{}, example1, example2)
Q: Can I generate specs for existing handlers?
A: Yes, define types that match your handlers and pass them to operations:
// Handler
func GetUser(id int) (*User, error) { ... }
// OpenAPI
openapi.GET("/users/:id",
openapi.WithResponse(200, User{}),
)
Q: How do I document error responses?
A: Use multiple WithResponse() calls:
openapi.GET("/users/:id",
openapi.WithResponse(200, User{}),
openapi.WithResponse(400, ErrorResponse{}),
openapi.WithResponse(404, ErrorResponse{}),
openapi.WithResponse(500, ErrorResponse{}),
)
Q: Can I use this with existing OpenAPI specs?
A: Use the validate package to validate external specs:
import "rivaas.dev/openapi/validate"
validator := validate.New()
err := validator.ValidateAuto(context.Background(), specJSON)
Getting Help
If you encounter issues not covered here:
- Check the pkg.go.dev documentation
- Review examples
- Search GitHub issues
- Open a new issue with a minimal reproduction
Next Steps