openapi

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

OpenAPI Package

Automatic 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 clean, type-safe API for building specifications with minimal boilerplate.

Features

  • Clean API - Builder-style API.Generate() method for specification generation
  • Type-Safe Version Selection - V30x and V31x constants with IDE autocomplete
  • Fluent HTTP Method Constructors - GET(), POST(), PUT(), etc. for clean operation definitions
  • Functional Options - Consistent With* pattern for all configuration
  • Type-Safe Warning Diagnostics - diag package for fine-grained warning control
  • Automatic Parameter Discovery - Extracts query, path, header, and cookie parameters from struct tags
  • Schema Generation - Converts Go types to OpenAPI schemas automatically
  • Swagger UI Configuration - Built-in, customizable Swagger UI settings
  • Semantic Operation IDs - Auto-generates operation IDs from HTTP methods and paths
  • Security Schemes - Support for Bearer, API Key, OAuth2, and OpenID Connect
  • Collision-Resistant Naming - Schema names use pkgname.TypeName format to prevent collisions
  • Built-in Validation - Validates generated specs against official OpenAPI meta-schemas
  • Standalone Validator - Validate external OpenAPI specs with pre-compiled schemas

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "rivaas.dev/openapi"
)

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

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
}

func main() {
    api := openapi.MustNew(
        openapi.WithTitle("My API", "1.0.0"),
        openapi.WithDescription("API for managing users"),
        openapi.WithServer("http://localhost:8080", "Local development"),
        openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
    )

    result, err := api.Generate(context.Background(),
        openapi.GET("/users/:id",
            openapi.WithSummary("Get user"),
            openapi.WithResponse(200, User{}),
            openapi.WithSecurity("bearerAuth"),
        ),
        openapi.POST("/users",
            openapi.WithSummary("Create user"),
            openapi.WithRequestBody(CreateUserRequest{}),
            openapi.WithResponse(201, User{}),
        ),
        openapi.DELETE("/users/:id",
            openapi.WithSummary("Delete user"),
            openapi.WithResponse(204, nil),
            openapi.WithSecurity("bearerAuth"),
        ),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Check for warnings (optional)
    if len(result.Warnings) > 0 {
        fmt.Printf("Generated with %d warnings\n", len(result.Warnings))
    }

    fmt.Println(string(result.JSON))
}

Configuration

Configuration is done exclusively through functional options with With* prefix.

Basic Configuration
api := openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
    openapi.WithDescription("API description"),
    openapi.WithInfoSummary("Short summary"), // 3.1.x only
    openapi.WithTermsOfService("https://example.com/terms"),
    openapi.WithVersion(openapi.V31x), // or openapi.V30x
)
Version Selection

The package supports two OpenAPI version families:

// Target OpenAPI 3.0.x (generates 3.0.4)
api := openapi.MustNew(
    openapi.WithTitle("API", "1.0.0"),
    openapi.WithVersion(openapi.V30x), // Default
)

// Target OpenAPI 3.1.x (generates 3.1.2)
api := openapi.MustNew(
    openapi.WithTitle("API", "1.0.0"),
    openapi.WithVersion(openapi.V31x),
)

The constants V30x and V31x represent version families - internally they map to specific versions (3.0.4 and 3.1.2) in the generated specification.

Servers
openapi.WithServer("https://api.example.com", "Production"),
openapi.WithServer("http://localhost:8080", "Local development"),

// With variables
openapi.WithServerVariable("baseUrl", "https://api.example.com", 
    []string{"https://api.example.com", "https://staging.example.com"},
    "Base URL for the API"),
Security Schemes
Bearer Authentication
openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
API Key Authentication
openapi.WithAPIKey(
    "apiKey",
    "X-API-Key",
    openapi.InHeader,
    "API key for authentication",
),
OAuth2
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",
        },
    },
),
OpenID Connect
openapi.WithOpenIDConnect(
    "openId",
    "https://example.com/.well-known/openid-configuration",
    "OpenID Connect authentication",
),
Tags
openapi.WithTag("users", "User management operations"),
openapi.WithTag("posts", "Post management operations"),
Swagger UI Configuration

Swagger UI options are nested under WithSwaggerUI() for cleaner namespacing:

openapi.MustNew(
    openapi.WithTitle("API", "1.0.0"),
    openapi.WithSwaggerUI("/docs",
        openapi.WithUIExpansion(openapi.ExpandList),
        openapi.WithUITryItOut(true),
        openapi.WithUIRequestSnippets(true, 
            openapi.SnippetCurlBash,
            openapi.SnippetCurlPowerShell,
        ),
        openapi.WithUISyntaxTheme(openapi.SyntaxThemeMonokai),
        openapi.WithUIFilter(true),
        openapi.WithUIPersistAuth(true),
    ),
)

// Or disable Swagger UI
openapi.WithoutSwaggerUI()

Defining Operations

The package provides HTTP method constructors for defining operations:

HTTP Method Constructors
openapi.GET("/users/:id", opts...)
openapi.POST("/users", opts...)
openapi.PUT("/users/:id", opts...)
openapi.PATCH("/users/:id", opts...)
openapi.DELETE("/users/:id", opts...)
openapi.HEAD("/users/:id", opts...)
openapi.OPTIONS("/users", opts...)
openapi.TRACE("/debug", opts...)
Operation Options

All operation options follow the With* naming convention for consistency:

Function Description
WithSummary(s) Set operation summary
WithDescription(s) Set operation description
WithOperationID(id) Set custom operation ID
WithRequestBody(type, opts...) Set request body type
WithResponse(status, type, opts...) Set response type for status code
WithQuery(name, example, opts...) Add query parameter
WithPath(name, example, opts...) Add path parameter
WithHeader(name, example, opts...) Add header parameter
WithTags(tags...) Add tags to operation
WithSecurity(scheme, scopes...) Add security requirement
WithDeprecated(bool) Mark operation as deprecated
Complete Operation Example
openapi.PUT("/users/:id",
    openapi.WithSummary("Update user"),
    openapi.WithDescription("Updates an existing user"),
    openapi.WithOperationID("updateUser"),
    openapi.WithRequestBody(UpdateUserRequest{}),
    openapi.WithResponse(200, User{}),
    openapi.WithResponse(404, ErrorResponse{}),
    openapi.WithResponse(400, ErrorResponse{}),
    openapi.WithTags("users"),
    openapi.WithSecurity("bearerAuth"),
    openapi.WithDeprecated(true),
)
Composable Operation Options

Use WithOptions() to create reusable option sets:

// Define reusable option sets
var (
    CommonErrors = openapi.WithOptions(
        openapi.WithResponse(400, Error{}),
        openapi.WithResponse(401, Error{}),
        openapi.WithResponse(500, Error{}),
    )
    
    UserEndpoint = openapi.WithOptions(
        openapi.WithTags("users"),
        openapi.WithSecurity("jwt"),
        CommonErrors,
    )
)

// Apply to operations
openapi.GET("/users/:id",
    UserEndpoint,
    openapi.WithSummary("Get user"),
    openapi.WithResponse(200, User{}),
)

openapi.POST("/users",
    UserEndpoint,
    openapi.WithSummary("Create user"),
    openapi.WithRequestBody(CreateUser{}),
    openapi.WithResponse(201, User{}),
)
Request Documentation
type GetUserRequest struct {
    ID     int    `path:"id" doc:"User ID" example:"123"`
    Expand string `query:"expand" doc:"Fields to expand" enum:"profile,settings"`
    Format string `header:"Accept" doc:"Response format" enum:"json,xml"`
}

result, err := api.Generate(context.Background(),
    openapi.GET("/users/:id",
        openapi.WithResponse(200, User{}),
    ),
)
Response Documentation
type UserResponse struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

type ErrorResponse struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}

result, err := api.Generate(context.Background(),
    openapi.GET("/users/:id",
        openapi.WithResponse(200, UserResponse{}),
        openapi.WithResponse(404, ErrorResponse{}),
        openapi.WithResponse(500, ErrorResponse{}),
    ),
)
Security Requirements
// Single security scheme
openapi.GET("/users/:id",
    openapi.WithSecurity("bearerAuth"),
)

// OAuth2 with scopes
openapi.POST("/users",
    openapi.WithSecurity("oauth2", "read", "write"),
)

// Multiple security schemes (OR)
openapi.DELETE("/users/:id",
    openapi.WithSecurity("bearerAuth"),
    openapi.WithSecurity("apiKey"),
)

Auto-Discovery

The package automatically discovers API parameters from struct tags.

Supported Tags
  • path:"name" - Path parameters (always required)
  • query:"name" - Query parameters
  • header:"name" - Header parameters
  • cookie:"name" - Cookie parameters
  • json:"name" - Request body fields
Additional Tags
  • doc:"description" - Parameter/field description
  • example:"value" - Example value
  • enum:"val1,val2" - Enum values (comma-separated)
  • validate:"required" - Validation rules (affects required in OpenAPI)
Struct Tag Examples
type CreateUserRequest struct {
    // Path parameter (always required)
    UserID int `path:"id" doc:"User ID" example:"123"`
    
    // Query parameters
    Page    int    `query:"page" doc:"Page number" example:"1" validate:"min=1"`
    PerPage int    `query:"per_page" doc:"Items per page" example:"20" validate:"min=1,max=100"`
    Format  string `query:"format" doc:"Response format" enum:"json,xml"`
    
    // Header parameters
    Accept string `header:"Accept" doc:"Content type" enum:"application/json,application/xml"`
    
    // Request body fields
    Name  string `json:"name" doc:"User name" example:"John Doe" validate:"required"`
    Email string `json:"email" doc:"User email" example:"[email protected]" validate:"required,email"`
    Age   *int   `json:"age,omitempty" doc:"User age" example:"30" validate:"min=0,max=150"`
}

Schema Generation

Go types are automatically converted to OpenAPI schemas:

Supported Types
  • Primitives: string, int, int64, float64, bool
  • Pointers: *string (nullable, optional)
  • Slices: []string, []int
  • Maps: map[string]int
  • Structs: Custom types (become object schemas)
  • Time: time.Time (becomes string with date-time format)
  • Embedded Structs: Fields from embedded structs are included
Schema Naming

Component schema names use the format pkgname.TypeName to prevent cross-package collisions:

// In package "api"
type User struct { ... }  // Becomes "api.User"

// In package "models"
type User struct { ... }  // Becomes "models.User"

Generating Specifications

Use api.Generate() with a context and variadic operation arguments:

api := openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
)

result, err := api.Generate(context.Background(),
    openapi.GET("/users",
        openapi.WithSummary("List users"),
        openapi.WithResponse(200, []User{}),
    ),
    openapi.GET("/users/:id",
        openapi.WithSummary("Get user"),
        openapi.WithResponse(200, User{}),
    ),
    openapi.POST("/users",
        openapi.WithSummary("Create user"),
        openapi.WithRequestBody(CreateUserRequest{}),
        openapi.WithResponse(201, User{}),
    ),
)
if err != nil {
    log.Fatal(err)
}

// result.JSON contains the OpenAPI specification as JSON
// result.YAML contains the OpenAPI specification as YAML
// result.Warnings contains any generation warnings
Working with Warnings

The package generates warnings when 3.1-only features are used with a 3.0 target:

result, err := api.Generate(context.Background(), ops...)
if err != nil {
    log.Fatal(err)
}

// Basic warning check
if len(result.Warnings) > 0 {
    fmt.Printf("Generated with %d warnings\n", len(result.Warnings))
}

// Iterate through warnings
for _, warn := range result.Warnings {
    fmt.Printf("[%s] %s\n", warn.Code(), warn.Message())
}
Type-Safe Warning Checks

Import the diag package for type-safe warning handling:

import "rivaas.dev/openapi/diag"

// Check for specific warning
if result.Warnings.Has(diag.WarnDownlevelWebhooks) {
    log.Warn("webhooks not supported in OpenAPI 3.0")
}

// Filter by category
downlevelWarnings := result.Warnings.FilterCategory(diag.CategoryDownlevel)
fmt.Printf("Downlevel warnings: %d\n", len(downlevelWarnings))

// Check for any of multiple codes
if result.Warnings.HasAny(
    diag.WarnDownlevelMutualTLS,
    diag.WarnDownlevelWebhooks,
) {
    log.Warn("Some 3.1 security features were dropped")
}

// Filter specific warnings
licenseWarnings := result.Warnings.Filter(diag.WarnDownlevelLicenseIdentifier)

// Exclude expected warnings
unexpected := result.Warnings.Exclude(diag.WarnDownlevelInfoSummary)

Advanced Usage

Custom Operation IDs
openapi.GET("/users/:id",
    openapi.WithOperationID("retrieveUser"),
    openapi.WithResponse(200, User{}),
)
Extensions

Add custom x-* extensions to various parts of the spec:

// Root-level extensions
api := openapi.MustNew(
    openapi.WithTitle("API", "1.0.0"),
    openapi.WithExtension("x-api-version", "v2"),
    openapi.WithExtension("x-custom-feature", true),
)
Strict Downlevel Mode

By default, using 3.1-only features with a 3.0 target generates warnings. Enable strict mode to error instead:

api := openapi.MustNew(
    openapi.WithTitle("API", "1.0.0"),
    openapi.WithVersion(openapi.V30x),
    openapi.WithStrictDownlevel(true), // Error on 3.1 features
    openapi.WithInfoSummary("Summary"), // This will cause an error
)

_, err := api.Generate(context.Background(), ops...)
// err will be non-nil due to strict mode violation
Validation

The package provides built-in validation against official OpenAPI meta-schemas:

// Enable validation (opt-in for performance)
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.Fatal(err) // Will fail if spec is invalid
}

Validation is disabled by default for performance. Enable it during development or in CI/CD pipelines.

Validate External Specs
import "rivaas.dev/openapi/validate"

// Auto-detect version
specJSON, _ := os.ReadFile("openapi.json")
validator := validate.New()
err := validator.Validate(context.Background(), specJSON, validate.V30)
if err != nil {
    log.Fatal(err)
}
Swagger UI Validation
// Use local validation (no external calls, 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),
)

Swagger UI Customization

Common Options
openapi.WithSwaggerUI(true, "/docs"),

// Document expansion
openapi.WithUIDocExpansion(openapi.DocExpansionList),     // list, full, none
openapi.WithUIModelsExpandDepth(1),                       // How deep to expand models
openapi.WithUIModelExpandDepth(1),                        // How deep to expand model

// Display options
openapi.WithUIDisplayOperationID(true),                   // Show operation IDs
openapi.WithUIDefaultModelRendering(openapi.ModelRenderingExample), // example, model

// Try it out
openapi.WithUITryItOut(true),                            // Enable "Try it out"
openapi.WithUIRequestSnippets(true,                      // Show request snippets
    openapi.SnippetCurlBash,
    openapi.SnippetCurlPowerShell,
    openapi.SnippetCurlCmd,
),
openapi.WithUIRequestSnippetsExpanded(true),             // Expand snippets by default
openapi.WithUIDisplayRequestDuration(true),              // Show request duration

// Filtering and sorting
openapi.WithUIFilter(true),                              // Enable filter box
openapi.WithUIMaxDisplayedTags(10),                      // Limit displayed tags
openapi.WithUIOperationsSorter(openapi.OperationsSorterAlpha), // alpha, method
openapi.WithUITagsSorter(openapi.TagsSorterAlpha),      // alpha

// Syntax highlighting
openapi.WithUISyntaxHighlight(true),                     // Enable syntax highlighting
openapi.WithUISyntaxTheme(openapi.SyntaxThemeMonokai),  // agate, monokai, etc.

// Authentication persistence
openapi.WithUIPersistAuth(true),                         // Persist auth across refreshes
openapi.WithUIWithCredentials(true),                    // Send credentials with requests

Complete Example

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "rivaas.dev/openapi"
)

type User struct {
    ID        int       `json:"id"`
    Name      string    `json:"name"`
    Email     string    `json:"email"`
    CreatedAt time.Time `json:"created_at"`
}

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
}

type GetUserRequest struct {
    ID int `path:"id" doc:"User ID"`
}

type ErrorResponse struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}

func main() {
    api := openapi.MustNew(
        openapi.WithTitle("User API", "1.0.0"),
        openapi.WithDescription("API for managing users"),
        openapi.WithServer("http://localhost:8080", "Local development"),
        openapi.WithServer("https://api.example.com", "Production"),
        openapi.WithBearerAuth("bearerAuth", "JWT authentication"),
        openapi.WithTag("users", "User management operations"),
    )

    result, err := api.Generate(context.Background(),
        openapi.GET("/users/:id",
            openapi.WithSummary("Get user"),
            openapi.WithDescription("Retrieves a user by ID"),
            openapi.WithResponse(200, User{}),
            openapi.WithResponse(404, ErrorResponse{}),
            openapi.WithTags("users"),
            openapi.WithSecurity("bearerAuth"),
        ),
        openapi.POST("/users",
            openapi.WithSummary("Create user"),
            openapi.WithDescription("Creates a new user"),
            openapi.WithRequestBody(CreateUserRequest{}),
            openapi.WithResponse(201, User{}),
            openapi.WithResponse(400, ErrorResponse{}),
            openapi.WithTags("users"),
            openapi.WithSecurity("bearerAuth"),
        ),
        openapi.DELETE("/users/:id",
            openapi.WithSummary("Delete user"),
            openapi.WithDescription("Deletes a user"),
            openapi.WithResponse(204, nil),
            openapi.WithTags("users"),
            openapi.WithSecurity("bearerAuth"),
        ),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Print any warnings
    for _, warn := range result.Warnings {
        log.Printf("Warning: %s", warn.Message())
    }

    // Output the specification
    fmt.Println(string(result.JSON))
}

API Reference

Full API documentation is available at pkg.go.dev/rivaas.dev/openapi.

Key Types
  • API - OpenAPI configuration (created via New() or MustNew())
  • Operation - An HTTP operation with method, path, and metadata
  • Result - Result of spec generation (JSON + YAML + Warnings)
  • Version - Type-safe OpenAPI version (V30x or V31x)
HTTP Method Constructors
  • GET(path, ...opts) Operation
  • POST(path, ...opts) Operation
  • PUT(path, ...opts) Operation
  • PATCH(path, ...opts) Operation
  • DELETE(path, ...opts) Operation
  • HEAD(path, ...opts) Operation
  • OPTIONS(path, ...opts) Operation
  • TRACE(path, ...opts) Operation
Key Functions
  • New(...Option) (*API, error) - Create API configuration with validation
  • MustNew(...Option) *API - Create API configuration (panics on error)
  • (api *API) Generate(ctx context.Context, ...Operation) (*Result, error) - Generate OpenAPI spec
Warning Diagnostics

Import rivaas.dev/openapi/diag for type-safe warning handling:

  • Warning interface - Individual warning with Code(), Message(), Path(), Category()
  • Warnings - Collection with helper methods (Has, Filter, FilterCategory, etc.)
  • WarningCode - Type-safe warning code constants (WarnDownlevelWebhooks, etc.)
  • WarningCategory - Warning categories (CategoryDownlevel, CategorySchema)

Troubleshooting

Schema Name Collisions

If you have types with the same name in different packages, the package automatically prefixes schema names with the package name:

// api.User becomes "api.User"
// models.User becomes "models.User"
Extension Validation

Extension keys must start with x-. In OpenAPI 3.1.x, keys starting with x-oai- or x-oas- are reserved and will be filtered out.

Version Compatibility

When using OpenAPI 3.0.x target, some 3.1.x features are automatically down-leveled with warnings:

  • info.summary - Dropped (3.1-only)
  • license.identifier - Dropped (3.1-only)
  • const in schemas - Converted to enum with single value
  • examples in schemas - Converted to single example
  • webhooks - Dropped (3.1-only)
  • mutualTLS security - Dropped (3.1-only)

Enable StrictDownlevel to error instead of warn:

api := openapi.MustNew(
    openapi.WithTitle("API", "1.0.0"),
    openapi.WithVersion(openapi.V30x),
    openapi.WithStrictDownlevel(true),
)

License

Apache License 2.0

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

Examples

Constants

View Source
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

View Source
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)

View Source
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)

View Source
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

View Source
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

View Source
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

View Source
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)

View Source
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

func MustNew(opts ...Option) *API

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

func New(opts ...Option) (*API, error)

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

func (a *API) Generate(ctx context.Context, ops ...Operation) (*Result, error)

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

func (a *API) UI() UIConfig

UI returns the Swagger UI configuration.

This provides access to UI settings for rendering the Swagger UI.

func (*API) Validate added in v0.4.0

func (a *API) Validate() error

Validate checks if the API is valid.

It ensures that required fields (title, version) are set and validates nested configurations like UI settings. Returns an error describing all validation failures.

Validation is automatically called by New and MustNew.

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

func (e Example) Description() string

Description returns the detailed description.

func (Example) ExternalValue

func (e Example) ExternalValue() string

ExternalValue returns the URL to an external example.

func (Example) IsExternal added in v0.2.0

func (e Example) IsExternal() bool

IsExternal returns true if this example uses an external URL.

func (Example) Name added in v0.2.0

func (e Example) Name() string

Name returns the unique identifier for this example.

func (Example) Summary

func (e Example) Summary() string

Summary returns the short description.

func (Example) Value

func (e Example) Value() any

Value returns the inline example value.

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

func WithBearerAuth(name, desc string) Option

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

func WithContact(name, url, email string) Option

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

func WithDefaultSecurity(scheme string, scopes ...string) Option

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

func WithExtension(key string, value any) Option

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

func WithExternalDocs(url, description string) Option

WithExternalDocs sets external documentation URL and optional description.

func WithInfoDescription added in v0.4.0

func WithInfoDescription(desc string) Option

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

func WithInfoExtension(key string, value any) Option

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

func WithInfoSummary(summary string) Option

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

func WithLicense(name, url string) Option

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

func WithLicenseIdentifier(name, identifier string) Option

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

func WithOpenIDConnect(name, url, desc string) Option

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

func WithServer(url, desc string) Option

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

func WithServerVariable(name, defaultValue string, enum []string, description string) Option

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

func WithSpecPath(path string) Option

WithSpecPath sets the HTTP path where the OpenAPI specification JSON is served.

Default: "/openapi.json"

Example:

openapi.WithSpecPath("/api/openapi.json")

func WithStrictDownlevel

func WithStrictDownlevel(strict bool) Option

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

func WithSwaggerUI(path string, opts ...UIOption) Option

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

func WithTag(name, desc string) Option

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

func WithTermsOfService(url string) Option

WithTermsOfService sets the Terms of Service URL/URI.

func WithTitle

func WithTitle(title, version string) Option

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

func WithValidation(enabled bool) Option

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

func WithVersion(version Version) Option

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

type ParamSpec = schema.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

type SecurityReq struct {
	Scheme string
	Scopes []string
}

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

func (c *UIConfig) ToConfigMap(specURL string) map[string]any

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

func (c *UIConfig) ToJSON(specURL string) (string, error)

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

func (c *UIConfig) Validate() error

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

func WithUIDeepLinking(enabled bool) UIOption

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

func WithUIDisplayOperationID(show bool) UIOption

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

func WithUIDisplayRequestDuration(show bool) UIOption

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

func WithUIFilter(enabled bool) UIOption

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

func WithUIMaxDisplayedTags(max int) UIOption

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

func WithUIModelExpandDepth(depth int) UIOption

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

func WithUIModelsExpandDepth(depth int) UIOption

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

func WithUIPersistAuth(enabled bool) UIOption

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

func WithUIRequestSnippetsExpanded(expanded bool) UIOption

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

func WithUIShowCommonExtensions(show bool) UIOption

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

func WithUIShowExtensions(show bool) UIOption

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

func WithUISyntaxHighlight(enabled bool) UIOption

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

func WithUITryItOut(enabled bool) UIOption

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

func WithUIValidator(url string) UIOption

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

func WithUIWithCredentials(enabled bool) UIOption

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.

const (
	// V30x targets OpenAPI 3.0.x (widely supported).
	V30x Version = "3.0.x"

	// V31x targets OpenAPI 3.1.x (latest, with JSON Schema 2020-12).
	V31x Version = "3.1.x"
)

OpenAPI specification versions.

func (Version) String added in v0.4.0

func (v Version) String() string

String returns the version as a string.

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.

Jump to

Keyboard shortcuts

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