openapi

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2026 License: Apache-2.0 Imports: 16 Imported by: 1

README

OpenAPI

Go Reference Go Report Card Coverage Go Version License

Automatic OpenAPI 3.0.4 and 3.1.2 specification generation for Go applications.

📚 Complete Documentation →

Documentation

This README provides a quick overview. For comprehensive guides, tutorials, and API reference:

Features

  • Clean API - API.Spec(ctx) and API.AddOperation(); operations from WithOperations or added incrementally
  • Type-Safe Version Selection - V30x and V31x constants
  • Operation Builders - WithGET(), WithPOST(), WithPUT(), etc.
  • Automatic Parameter Discovery - Extracts parameters from struct tags
  • Schema Generation - Converts Go types to OpenAPI schemas
  • Swagger UI Configuration - Built-in, customizable UI
  • Type-Safe Diagnostics - diag package for warning control
  • Built-in Validation - Validates against official meta-schemas

Installation

go get rivaas.dev/openapi

Requires Go 1.25+

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"),
    )
    getOp, _ := openapi.WithGET("/users/:id", openapi.WithSummary("Get user"), openapi.WithResponse(200, User{}), openapi.WithSecurity("bearerAuth"))
    postOp, _ := openapi.WithPOST("/users", openapi.WithSummary("Create user"), openapi.WithRequest(CreateUserRequest{}), openapi.WithResponse(201, User{}))
    delOp, _ := openapi.WithDELETE("/users/:id", openapi.WithSummary("Delete user"), openapi.WithResponse(204, nil), openapi.WithSecurity("bearerAuth"))
    if err := api.AddOperation(getOp, postOp, delOp); err != nil {
        log.Fatal(err)
    }

    result, err := api.Spec(context.Background())
    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))
}

See more examples →

Learn More

Contributing

Contributions are welcome! Please see the main repository for contribution guidelines.

License

Apache License 2.0 - see LICENSE for details.


Part of the Rivaas web framework ecosystem.

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

  • Operation builders (WithGET, WithPOST, WithPUT, 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

Declarative: pass operations at construction.

api := openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
    openapi.WithDescription("API description"),
    openapi.WithBearerAuth("bearerAuth", "JWT"),
    openapi.WithServer("http://localhost:8080", "Local development"),
    openapi.WithOperations(
        openapi.WithGET("/users/:id", openapi.WithSummary("Get user"), openapi.WithResponse(200, UserResponse{}), openapi.WithTags("users"), openapi.WithSecurity("bearerAuth")),
        openapi.WithPOST("/users", openapi.WithSummary("Create user"), openapi.WithRequest(CreateUserRequest{}), openapi.WithResponse(201, UserResponse{}), openapi.WithTags("users")),
    ),
)
result, err := api.Spec(context.Background())

Incremental: add operations after construction.

api := openapi.MustNew(openapi.WithTitle("My API", "1.0.0"))
op, _ := openapi.WithGET("/users/:id", openapi.WithSummary("Get user"), openapi.WithResponse(200, UserResponse{}))
_ = api.AddOperation(op) // returns error if operation is invalid
result, err := api.Spec(context.Background())

Configuration vs Operations

The package uses two distinct types of options, both with the With* prefix:

API options configure the spec (use in New/MustNew):

  • WithTitle, WithDescription, WithServer, WithBearerAuth

Operation options configure routes (use in WithGET, WithPOST, etc.):

  • WithSummary, WithDescription, WithResponse, WithTags, WithSecurity

API configuration is read-only after creation. Use getters to read values.

Example:

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

openapi.WithGET("/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
  • path: Path parameters
  • header: Header parameters
  • cookie: Cookie parameters
  • json: Request body fields

Example:

type GetUserRequest struct {
    ID     int    `path:"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:

api := openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
    openapi.WithValidateSpec(true), // Enable validation
)

result, err := api.Spec(context.Background())
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)
}

Standalone Usage

This package works independently without the full Rivaas framework. Use it with any Go HTTP handler (net/http, Gin, Echo, etc.).

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
	)

	//nolint:errcheck // ignore error for example
	op, _ := openapi.WithGET("/health", openapi.WithResponse(200, map[string]string{}))
	//nolint:errcheck // ignore error for example
	api.AddOperation(op)
	//nolint:errcheck // ignore error for example
	result, _ := api.Spec(context.Background())

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

	//
	op, err := openapi.WithGET("/health", openapi.WithResponse(200, map[string]string{}))
	if err != nil {
		panic(err)
	}
	if addErr := api.AddOperation(op); addErr != nil {
		panic(addErr)
	}
	result, err := api.Spec(context.Background())
	if err != nil {
		panic(err)
	}

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

	op, err := openapi.WithGET("/health", openapi.WithResponse(200, map[string]string{}))
	if err != nil {
		panic(err)
	}
	if addErr := api.AddOperation(op); addErr != nil {
		panic(addErr)
	}
	_, err = api.Spec(context.Background())
	// 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 WithValidateSpec 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 {
	// contains filtered or unexported fields
}

API holds OpenAPI configuration and defines an API specification. Configuration is read-only after creation; use getters to read values. Operations can be set at construction via WithOperations or added later via API.AddOperation. 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.WithDescription("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) AddOperation added in v0.6.0

func (a *API) AddOperation(ops ...Operation) error

AddOperation adds one or more operations to the API. Safe for concurrent use. Call [Spec] to generate the spec including these operations. Returns an error if any operation has empty Method or Path or an invalid path format; on error no operations are added.

func (*API) DefaultSecurity added in v0.4.0

func (a *API) DefaultSecurity() []SecurityRequirement

DefaultSecurity returns the default security requirements. Do not modify the returned slice.

func (*API) Extensions added in v0.4.0

func (a *API) Extensions() map[string]any

Extensions returns the root-level specification extensions. Do not modify the returned map.

func (*API) ExternalDocs added in v0.4.0

func (a *API) ExternalDocs() *ExternalDocs

ExternalDocs returns the external documentation link, or nil.

func (*API) Info added in v0.4.0

func (a *API) Info() Info

Info returns the API metadata (title, version, description, contact, license). Do not modify the returned value.

func (*API) SecuritySchemes added in v0.4.0

func (a *API) SecuritySchemes() map[string]*SecurityScheme

SecuritySchemes returns the security schemes map. Do not modify the returned map.

func (*API) ServeUI added in v0.4.0

func (a *API) ServeUI() bool

ServeUI returns whether Swagger UI is enabled.

func (*API) Servers added in v0.4.0

func (a *API) Servers() []Server

Servers returns the list of server URLs. Do not modify the returned slice or its elements.

func (*API) Spec added in v0.6.0

func (a *API) Spec(ctx context.Context) (*Result, error)

Spec produces an OpenAPI specification from the API's current configuration and operations (from WithOperations and/or API.AddOperation). Pure function of current API state; no side effects. Caching is the caller's responsibility.

Example:

api := openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
    openapi.WithOperations(
        openapi.WithGET("/users/:id", openapi.WithSummary("Get user"), openapi.WithResponse(200, User{})),
        openapi.WithPOST("/users", openapi.WithSummary("Create user"), openapi.WithRequest(CreateUserRequest{}), openapi.WithResponse(201, User{})),
    ),
)
spec, err := api.Spec(ctx)
// or: api.AddOperation(openapi.WithGET(...)); spec, err := api.Spec(ctx)
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"),
	)

	op, err := openapi.WithGET("/users/:id",
		openapi.WithSummary("Get user"),
		openapi.WithOperationDescription("Retrieves a user by ID"),
		openapi.WithTags("users"),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if addErr := api.AddOperation(op); addErr != nil {
		fmt.Printf("Error: %v\n", addErr)
		return
	}
	result, err := api.Spec(context.Background())
	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) SpecPath added in v0.4.0

func (a *API) SpecPath() string

SpecPath returns the HTTP path where the OpenAPI specification JSON is served.

func (*API) StrictDownlevel added in v0.4.0

func (a *API) StrictDownlevel() bool

StrictDownlevel returns whether projection errors (instead of warns) for 3.1-only features when targeting 3.0.

func (*API) Tags added in v0.4.0

func (a *API) Tags() []Tag

Tags returns the tags. Do not modify the returned slice or its elements.

func (*API) UI added in v0.4.0

func (a *API) UI() UISnapshot

UI returns a read-only snapshot of the Swagger UI configuration.

Use the returned UISnapshot for rendering (e.g. ToJSON); do not use it for construction.

func (*API) UIPath added in v0.4.0

func (a *API) UIPath() string

UIPath returns the HTTP path where Swagger UI is served.

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. Validate uses the same rules as New; it does not validate operations (see [AddOperation] for operation validation at add time).

func (*API) ValidateSpec added in v0.4.0

func (a *API) ValidateSpec() bool

ValidateSpec returns whether JSON Schema validation of generated specs is enabled.

func (*API) Version added in v0.4.0

func (a *API) Version() Version

Version returns the target OpenAPI version (V30x or V31x).

type Contact

type Contact struct {
	Name  string
	URL   string
	Email string
}

Contact holds contact information for the API.

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 ExternalDocs

type ExternalDocs struct {
	URL         string
	Description string
}

ExternalDocs holds external documentation link. Returned by API.ExternalDocs. Do not modify.

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 Info

type Info struct {
	Title          string
	Summary        string
	Description    string
	TermsOfService string
	Version        string
	Contact        *Contact
	License        *License
	Extensions     map[string]any
}

Info holds API metadata (title, version, description, contact, license). Returned by API.Info. Do not modify.

type License

type License struct {
	Name       string // License name
	Identifier string // SPDX identifier (3.1+), mutually exclusive with URL
	URL        string // License URL (3.0), mutually exclusive with Identifier
}

License holds license information for the API.

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 OAuth2FlowInfo added in v0.6.0

type OAuth2FlowInfo struct {
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	Scopes           map[string]string
}

OAuth2FlowInfo holds a single OAuth2 flow's URLs and scopes.

type OAuth2Flows added in v0.6.0

type OAuth2Flows struct {
	AuthorizationCode *OAuth2FlowInfo
	Implicit          *OAuth2FlowInfo
	Password          *OAuth2FlowInfo
	ClientCredentials *OAuth2FlowInfo
}

OAuth2Flows holds OAuth2 flow configuration for display.

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 WithGET, WithPOST, WithPUT, WithPATCH, WithDELETE, WithHEAD, WithOPTIONS, or WithOp.

func WithDELETE added in v0.6.0

func WithDELETE(path string, opts ...OperationOption) (Operation, error)

WithDELETE creates an Operation for a DELETE request.

Example:

openapi.WithDELETE("/users/:id",
    openapi.WithSummary("Delete user"),
    openapi.WithResponse(204, nil),
)
Example

ExampleWithDELETE demonstrates creating a DELETE operation.

package main

import (
	"fmt"
	"net/http"

	"rivaas.dev/openapi"
)

func main() {
	op, err := openapi.WithDELETE("/users/:id",
		openapi.WithSummary("Delete user"),
		openapi.WithResponse(http.StatusNoContent, nil),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output:
Method: DELETE, Path: /users/:id

func WithGET added in v0.6.0

func WithGET(path string, opts ...OperationOption) (Operation, error)

WithGET creates an Operation for a GET request.

Example:

openapi.WithGET("/users/:id",
    openapi.WithSummary("Get user"),
    openapi.WithResponse(200, User{}),
)
Example

ExampleWithGET demonstrates creating a GET operation.

package main

import (
	"fmt"
	"net/http"

	"rivaas.dev/openapi"
)

func main() {
	op, err := openapi.WithGET("/users/:id",
		openapi.WithSummary("Get user"),
		openapi.WithOperationDescription("Retrieves a user by ID"),
		openapi.WithResponse(http.StatusOK, User{}),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	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 WithHEAD added in v0.6.0

func WithHEAD(path string, opts ...OperationOption) (Operation, error)

WithHEAD creates an Operation for a HEAD request.

Example:

openapi.WithHEAD("/users/:id",
    openapi.WithSummary("Check user exists"),
)

func WithOPTIONS added in v0.6.0

func WithOPTIONS(path string, opts ...OperationOption) (Operation, error)

WithOPTIONS creates an Operation for an OPTIONS request.

Example:

openapi.WithOPTIONS("/users",
    openapi.WithSummary("Get supported methods"),
)

func WithOp added in v0.6.0

func WithOp(method, path string, opts ...OperationOption) (Operation, error)

WithOp creates an Operation with a custom HTTP method. Prefer WithGET, WithPOST, etc. when possible.

Example:

openapi.WithOp("CUSTOM", "/resource",
    openapi.WithSummary("Custom operation"),
)

func WithPATCH added in v0.6.0

func WithPATCH(path string, opts ...OperationOption) (Operation, error)

WithPATCH creates an Operation for a PATCH request.

Example:

openapi.WithPATCH("/users/:id",
    openapi.WithSummary("Partially update user"),
    openapi.WithRequest(PatchUserRequest{}),
    openapi.WithResponse(200, User{}),
)

func WithPOST added in v0.6.0

func WithPOST(path string, opts ...OperationOption) (Operation, error)

WithPOST creates an Operation for a POST request.

Example:

openapi.WithPOST("/users",
    openapi.WithSummary("Create user"),
    openapi.WithRequest(CreateUserRequest{}),
    openapi.WithResponse(201, User{}),
)
Example

ExampleWithPOST demonstrates creating a POST operation.

package main

import (
	"fmt"
	"net/http"

	"rivaas.dev/openapi"
)

func main() {
	op, err := openapi.WithPOST("/users",
		openapi.WithSummary("Create user"),
		openapi.WithRequest(CreateUserRequest{}),
		openapi.WithResponse(http.StatusCreated, User{}),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	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 WithPUT added in v0.6.0

func WithPUT(path string, opts ...OperationOption) (Operation, error)

WithPUT creates an Operation for a PUT request.

Example:

openapi.WithPUT("/users/:id",
    openapi.WithSummary("Update user"),
    openapi.WithRequest(UpdateUserRequest{}),
    openapi.WithResponse(200, User{}),
)

func WithTRACE added in v0.6.0

func WithTRACE(path string, opts ...OperationOption) (Operation, error)

WithTRACE creates an Operation for a TRACE request.

Example:

openapi.WithTRACE("/users/:id",
    openapi.WithSummary("Trace request"),
)

type OperationOption added in v0.4.0

type OperationOption func(*operationDoc)

OperationOption configures an OpenAPI operation. Use with WithGET, WithPOST, WithPUT, etc.

func WithConsumes added in v0.4.0

func WithConsumes(contentTypes ...string) OperationOption

WithConsumes sets the content types that this operation accepts.

Example:

openapi.WithPOST("/users",
    openapi.WithConsumes("application/xml", "application/json"),
)

func WithDeprecated added in v0.4.0

func WithDeprecated(deprecated ...bool) OperationOption

WithDeprecated marks the operation as deprecated. WithDeprecated() is shorthand for WithDeprecated(true).

Example:

openapi.WithGET("/old-endpoint",
    openapi.WithDeprecated(),
)
Example

ExampleWithDeprecated demonstrates marking an operation as deprecated.

package main

import (
	"fmt"

	"rivaas.dev/openapi"
)

func main() {
	op, err := openapi.WithGET("/old-endpoint",
		openapi.WithSummary("Old endpoint"),
		openapi.WithDeprecated(),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Method: %s, Path: %s\n", op.Method, op.Path)
}
Output:
Method: GET, Path: /old-endpoint

func WithOperationDescription added in v0.6.0

func WithOperationDescription(s string) OperationOption

WithOperationDescription sets the operation description.

Example:

openapi.WithGET("/users/:id",
    openapi.WithOperationDescription("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.WithGET("/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.WithGET("/users/:id",
    openapi.WithOperationID("getUserById"),
)

func WithOptions added in v0.4.0

func WithOptions(opts ...OperationOption) (OperationOption, error)

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.

WithOptions returns an error if any element of opts is nil (validation at compose time).

Example:

// Define reusable option sets (check error at init)
CommonErrors, err := openapi.WithOptions(
    openapi.WithResponse(400, Error{}),
    openapi.WithResponse(401, Error{}),
    openapi.WithResponse(500, Error{}),
)
if err != nil {
    // handle err
}
UserEndpoint, err := openapi.WithOptions(
    openapi.WithTags("users"),
    AuthRequired,
    CommonErrors,
)
if err != nil {
    // handle err
}

// Apply composed options to operations
openapi.WithGET("/users/:id",
    UserEndpoint,
    openapi.WithSummary("Get user"),
    openapi.WithResponse(200, User{}),
)
openapi.WithPOST("/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.WithGET("/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.WithPOST("/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, err := openapi.WithPOST("/users",
		openapi.WithSummary("Create user"),
		openapi.WithRequest(CreateUserRequest{}),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	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.WithGET("/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, err := openapi.WithGET("/users/:id",
		openapi.WithSummary("Get user"),
		openapi.WithResponse(200, User{}),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	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.WithGET("/users/:id",
    openapi.WithSecurity("bearerAuth"),
)

openapi.WithPOST("/users",
    openapi.WithSecurity("oauth2", "read:users", "write:users"),
)
Example

ExampleWithSecurity demonstrates adding security requirements.

package main

import (
	"fmt"

	"rivaas.dev/openapi"
)

func main() {
	op, err := openapi.WithGET("/users/:id",
		openapi.WithSecurity("bearerAuth"),
		openapi.WithSecurity("oauth2", "read:users", "write:users"),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	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.WithGET("/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, err := openapi.WithGET("/users", openapi.WithSummary("List all users"))
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	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.WithGET("/users/:id",
    openapi.WithTags("users", "authentication"),
)
Example

ExampleWithTags demonstrates adding tags to an operation.

package main

import (
	"fmt"

	"rivaas.dev/openapi"
)

func main() {
	op, err := openapi.WithGET("/users/:id", openapi.WithTags("users", "admin"))
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

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

Option configures OpenAPI behavior using the functional options pattern. Options apply to an internal config struct; the constructor builds the API from the validated config. 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 an 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 a 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", "support@example.com")

func WithDefaultSecurity

func WithDefaultSecurity(requirements ...SecurityReq) Option

WithDefaultSecurity sets default security requirements applied to all operations.

Operations can override this via WithSecurity on the operation.

Example:

openapi.WithDefaultSecurity(openapi.RequireSecurity("bearerAuth"))
openapi.WithDefaultSecurity(openapi.RequireSecurity("oauth2", "read", "write"))

func WithDescription

func WithDescription(desc string) Option

WithDescription sets the API description in the Info object.

The description supports Markdown formatting and appears in the OpenAPI spec and Swagger UI.

Example:

openapi.WithDescription("A RESTful API for managing users and their profiles.")

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 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 WithOAuth2AuthorizationCode added in v0.6.0

func WithOAuth2AuthorizationCode(name, desc, authURL, tokenURL, refreshURL string, scopes map[string]string) Option

WithOAuth2AuthorizationCode adds the OAuth2 authorization code flow to the named scheme.

authURL and tokenURL are required. refreshURL is optional. scopes maps scope names to descriptions (can be nil or empty). If a scheme with the same name already exists (e.g. from another flow option), the flow is merged into it.

Example:

openapi.WithOAuth2AuthorizationCode("oauth2", "OAuth2 authentication",
    "https://example.com/oauth/authorize", "https://example.com/oauth/token", "https://example.com/oauth/refresh",
    map[string]string{"read": "Read access", "write": "Write access"})

func WithOAuth2ClientCredentials added in v0.6.0

func WithOAuth2ClientCredentials(name, desc, tokenURL, refreshURL string, scopes map[string]string) Option

WithOAuth2ClientCredentials adds the OAuth2 client credentials flow to the named scheme.

tokenURL is required. refreshURL is optional. scopes maps scope names to descriptions (can be nil or empty).

Example:

openapi.WithOAuth2ClientCredentials("oauth2", "OAuth2 authentication",
    "https://example.com/oauth/token", "",
    map[string]string{"api": "API access"})

func WithOAuth2Implicit added in v0.6.0

func WithOAuth2Implicit(name, desc, authURL, refreshURL string, scopes map[string]string) Option

WithOAuth2Implicit adds the OAuth2 implicit flow to the named scheme.

authURL is required. refreshURL is optional. scopes maps scope names to descriptions (can be nil or empty).

Example:

openapi.WithOAuth2Implicit("oauth2", "OAuth2 authentication",
    "https://example.com/oauth/authorize", "https://example.com/oauth/refresh",
    map[string]string{"read": "Read access"})

func WithOAuth2Password added in v0.6.0

func WithOAuth2Password(name, desc, tokenURL, refreshURL string, scopes map[string]string) Option

WithOAuth2Password adds the OAuth2 resource owner password flow to the named scheme.

tokenURL is required. refreshURL is optional. scopes maps scope names to descriptions (can be nil or empty).

Example:

openapi.WithOAuth2Password("oauth2", "OAuth2 authentication",
    "https://example.com/oauth/token", "https://example.com/oauth/refresh",
    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 WithOperations added in v0.6.0

func WithOperations(ops ...Operation) Option

WithOperations sets the operations included in the API at construction. Can be empty. Operations can also be added after construction via API.AddOperation.

Example:

openapi.MustNew(
    openapi.WithTitle("My API", "1.0.0"),
    openapi.WithOperations(
        openapi.WithGET("/users/:id", openapi.WithSummary("Get user"), openapi.WithResponse(200, User{})),
        openapi.WithPOST("/users", openapi.WithSummary("Create user"), openapi.WithRequest(CreateUserRequest{}), openapi.WithResponse(201, User{})),
    ),
)

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.DocExpansionList),
        openapi.WithUITryItOut(true),
        openapi.WithUISyntaxTheme(openapi.SyntaxThemeMonokai),
    ),
)

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 WithTitleIfDefault added in v0.6.0

func WithTitleIfDefault(title, version string) Option

WithTitleIfDefault sets the API title and version only if they are still the defaults ("API" and "1.0.0"). Used by the app package to inject service name/version when the user has not set a custom title. Option order does not matter.

Example (typically used by app, not by users directly):

openapi.New(append(userOpts, openapi.WithTitleIfDefault(serviceName, serviceVersion))...)

func WithValidateSpec added in v0.6.0

func WithValidateSpec(validate bool) Option

WithValidateSpec enables or disables JSON Schema validation of the generated OpenAPI spec.

When enabled, Spec() 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. Enable for development and testing to catch errors early.

Default: false

Example:

openapi.WithValidateSpec(true)

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

func RequireSecurity added in v0.6.0

func RequireSecurity(scheme string, scopes ...string) SecurityReq

RequireSecurity builds a SecurityReq for use with WithDefaultSecurity or WithSecurity.

Example:

openapi.WithDefaultSecurity(
    openapi.RequireSecurity("bearerAuth"),
    openapi.RequireSecurity("oauth2", "read", "write"),
)

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement holds required security schemes and optional scopes (scheme name -> scopes). Returned by API.DefaultSecurity. Use RequireSecurity to build requirements for WithDefaultSecurity.

type SecurityScheme

type SecurityScheme struct {
	Type             string
	Description      string
	Name             string
	In               string
	Scheme           string
	BearerFormat     string
	OpenIDConnectURL string
	Flows            *OAuth2Flows
}

SecurityScheme holds a security scheme definition. Returned by API.SecuritySchemes. Do not modify. For oauth2 schemes, Flows may be set. For apiKey: Name and In. For http: Scheme and BearerFormat. For openIdConnect: OpenIDConnectURL.

type Server

type Server struct {
	URL         string
	Description string
	Variables   map[string]*ServerVariable
}

Server holds a server URL and optional description and variables. Returned by API.Servers. Do not modify.

type ServerVariable

type ServerVariable struct {
	Enum        []string
	Default     string
	Description string
}

ServerVariable holds a variable for server URL template substitution.

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 Tag

type Tag struct {
	Name        string
	Description string
}

Tag holds tag metadata. Returned by API.Tags. Do not modify.

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

  • DocExpansionList: Expand only tags (default)
  • DocExpansionFull: Expand tags and operations
  • DocExpansionNone: Collapse everything

Example:

openapi.WithSwaggerUI("/docs",
    openapi.WithUIExpansion(openapi.DocExpansionFull),
)

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 UISnapshot added in v0.6.0

type UISnapshot interface {
	ToJSON(specPath string) (string, error)
}

UISnapshot is the read-only contract returned by API.UI. Use it to render Swagger UI (e.g. via ToJSON); do not use for construction. Configuration is done only via UIOption and New or MustNew.

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
Sponsor
SponsoredKunjungi sekarang
Promo