Documentation
¶
Index ¶
- type API
- type OAuth2Flow
- type OAuthFlowType
- type Operation
- func DELETE(path string, opts ...OperationDocOption) Operation
- func GET(path string, opts ...OperationDocOption) Operation
- func HEAD(path string, opts ...OperationDocOption) Operation
- func OPTIONS(path string, opts ...OperationDocOption) Operation
- func PATCH(path string, opts ...OperationDocOption) Operation
- func POST(path string, opts ...OperationDocOption) Operation
- func PUT(path string, opts ...OperationDocOption) Operation
- func TRACE(path string, opts ...OperationDocOption) Operation
- type OperationDocOption
- func WithConsumes(contentTypes ...string) OperationDocOption
- func WithDeprecated() OperationDocOption
- func WithDescription(s string) OperationDocOption
- func WithOperationExtension(key string, value any) OperationDocOption
- func WithOperationID(id string) OperationDocOption
- func WithOptions(opts ...OperationDocOption) OperationDocOption
- func WithProduces(contentTypes ...string) OperationDocOption
- func WithRequest(req any, examples ...example.Example) OperationDocOption
- func WithResponse(status int, resp any, examples ...example.Example) OperationDocOption
- func WithSecurity(scheme string, scopes ...string) OperationDocOption
- func WithSummary(s string) OperationDocOption
- func WithTags(tags ...string) OperationDocOption
- type Option
- func WithAPIKey(name, paramName string, in ParameterLocation, desc string) Option
- func WithBearerAuth(name, desc string) Option
- func WithContact(name, url, email string) Option
- func WithDefaultSecurity(scheme string, scopes ...string) Option
- func WithExtension(key string, value any) Option
- func WithExternalDocs(url, description string) Option
- func WithInfoDescription(desc string) Option
- func WithInfoExtension(key string, value any) Option
- func WithInfoSummary(summary string) Option
- func WithInfoTitle(title string) Option
- func WithInfoVersion(version string) Option
- func WithLicense(name, url string) Option
- func WithLicenseIdentifier(name, identifier string) Option
- func WithOAuth2(name, desc string, flows ...OAuth2Flow) Option
- func WithOpenIDConnect(name, url, desc string) Option
- func WithSchemaPrefix(prefix string) Option
- func WithServer(url string, opts ...ServerOption) Option
- func WithStrictDownlevel(strict bool) Option
- func WithTag(name, desc string) Option
- func WithTagConfig(cfg config.TagConfig) Option
- func WithTermsOfService(url string) Option
- func WithValidation(enabled bool) Option
- func WithVersion(version string) Option
- type ParameterLocation
- type Result
- type SecurityReq
- type ServerOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type API ¶
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.
Version string
// StrictDownlevel causes projection to error (instead of warn) when
// 3.1-only features are used with a 3.0 target.
// Default: false
StrictDownlevel 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
// SchemaPrefix is the prefix for the OpenAPI schema.
SchemaPrefix string
// TagConfig configures struct tag names used for OpenAPI schema generation.
// If not set, uses default tag names (schema, body, openapi, validate, default, requires).
TagConfig config.TagConfig
// 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 NewAPI ¶
NewAPI creates a new OpenAPI API.
Example:
api := openapi.NewAPI(
openapi.WithInfoTitle("My API"),
openapi.WithInfoVersion("1.0.0"),
openapi.WithInfoDescription("API description"),
)
func (*API) Generate ¶
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))
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 ¶
func DELETE(path string, opts ...OperationDocOption) Operation
DELETE creates an Operation for a DELETE request.
Example:
openapi.DELETE("/users/:id",
openapi.WithSummary("Delete user"),
openapi.WithResponse(204, nil),
)
func GET ¶
func GET(path string, opts ...OperationDocOption) Operation
GET creates an Operation for a GET request.
Example:
openapi.GET("/users/:id",
openapi.WithSummary("Get user"),
openapi.WithResponse(200, User{}),
)
func HEAD ¶
func HEAD(path string, opts ...OperationDocOption) Operation
HEAD creates an Operation for a HEAD request.
Example:
openapi.HEAD("/users/:id",
openapi.WithSummary("Check user exists"),
)
func OPTIONS ¶
func OPTIONS(path string, opts ...OperationDocOption) Operation
OPTIONS creates an Operation for an OPTIONS request.
Example:
openapi.OPTIONS("/users",
openapi.WithSummary("Get supported methods"),
)
func PATCH ¶
func PATCH(path string, opts ...OperationDocOption) 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 ¶
func POST(path string, opts ...OperationDocOption) Operation
POST creates an Operation for a POST request.
Example:
openapi.POST("/users",
openapi.WithSummary("Create user"),
openapi.WithRequest(CreateUserRequest{}),
openapi.WithResponse(201, User{}),
)
func PUT ¶
func PUT(path string, opts ...OperationDocOption) 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 ¶
func TRACE(path string, opts ...OperationDocOption) Operation
TRACE creates an Operation for a TRACE request.
Example:
openapi.TRACE("/users/:id",
openapi.WithSummary("Trace request"),
)
type OperationDocOption ¶
type OperationDocOption func(*operationDoc)
OperationDocOption configures an OpenAPI operation. Use with HTTP method constructors like GET, POST, PUT, etc.
func WithConsumes ¶
func WithConsumes(contentTypes ...string) OperationDocOption
WithConsumes sets the content types that this operation accepts.
Example:
openapi.POST("/users",
openapi.WithConsumes("application/xml", "application/json"),
)
func WithDeprecated ¶
func WithDeprecated() OperationDocOption
WithDeprecated marks the operation as deprecated.
Example:
openapi.GET("/old-endpoint",
openapi.WithDeprecated(),
)
func WithDescription ¶
func WithDescription(s string) OperationDocOption
WithDescription sets the operation description.
Example:
openapi.GET("/users/:id",
openapi.WithDescription("Retrieves a user by their unique identifier"),
)
func WithOperationExtension ¶
func WithOperationExtension(key string, value any) OperationDocOption
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 ¶
func WithOperationID(id string) OperationDocOption
WithOperationID sets a custom operation ID.
Example:
openapi.GET("/users/:id",
openapi.WithOperationID("getUserById"),
)
func WithOptions ¶
func WithOptions(opts ...OperationDocOption) OperationDocOption
WithOptions composes multiple OperationDocOptions 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 ¶
func WithProduces(contentTypes ...string) OperationDocOption
WithProduces sets the content types that this operation returns.
Example:
openapi.GET("/users/:id",
openapi.WithProduces("application/xml", "application/json"),
)
func WithRequest ¶
func WithRequest(req any, examples ...example.Example) OperationDocOption
WithRequest sets the request type and optionally provides examples.
Example:
openapi.POST("/users",
openapi.WithRequest(CreateUserRequest{}),
)
func WithResponse ¶
func WithResponse(status int, resp any, examples ...example.Example) OperationDocOption
WithResponse sets the response schema and examples for a status code.
Example:
openapi.GET("/users/:id",
openapi.WithResponse(200, User{}),
openapi.WithResponse(404, ErrorResponse{}),
)
With named examples:
openapi.GET("/users/:id",
openapi.WithResponse(200, User{},
example.New("success", User{ID: 1, Name: "John"}),
example.New("admin", User{ID: 2, Name: "Admin"},
example.WithSummary("Admin user"),
example.WithDescription("User with elevated permissions"),
),
),
)
func WithSecurity ¶
func WithSecurity(scheme string, scopes ...string) OperationDocOption
WithSecurity adds a security requirement.
Example:
openapi.GET("/users/:id",
openapi.WithSecurity("bearerAuth"),
)
openapi.POST("/users",
openapi.WithSecurity("oauth2", "read:users", "write:users"),
)
func WithSummary ¶
func WithSummary(s string) OperationDocOption
WithSummary sets the operation summary.
Example:
openapi.GET("/users/:id",
openapi.WithSummary("Get user by ID"),
)
func WithTags ¶
func WithTags(tags ...string) OperationDocOption
WithTags adds tags to the operation.
Example:
openapi.GET("/users/:id",
openapi.WithTags("users", "authentication"),
)
type Option ¶
type Option func(*API)
Option configures OpenAPI behavior using the functional options pattern. Options are applied in order, with later options potentially overriding earlier ones.
func WithAPIKey ¶
func WithAPIKey(name, paramName string, in ParameterLocation, desc string) Option
WithAPIKey adds API key authentication scheme.
Parameters:
- name: Scheme name used in security requirements
- paramName: Name of the header/query parameter (e.g., "X-API-Key")
- in: Location of the API key - use InHeader, InQuery, or InCookie
- desc: Description shown in Swagger UI
Example:
openapi.WithAPIKey("apiKey", "X-API-Key", openapi.InHeader, "API key in X-API-Key header")
func WithBearerAuth ¶
WithBearerAuth adds Bearer (JWT) authentication scheme.
The name is used to reference this scheme in security requirements. The description appears in Swagger UI to help users understand the authentication.
Example:
openapi.WithBearerAuth("bearerAuth", "JWT token authentication. Format: Bearer <token>")
Then use in routes:
app.GET("/protected", handler).Bearer()
func WithContact ¶
WithContact sets contact information for the API.
All parameters are optional. Empty strings are omitted from the specification.
Example:
openapi.WithContact("API Support", "https://example.com/support", "[email protected]")
func WithDefaultSecurity ¶
WithDefaultSecurity sets default security requirements applied to all operations.
Operations can override this by specifying their own security requirements using RouteWrapper.Security() or RouteWrapper.Bearer().
Example:
// Apply Bearer auth to all operations by default
openapi.WithDefaultSecurity("bearerAuth")
// Apply OAuth with specific scopes
openapi.WithDefaultSecurity("oauth2", "read", "write")
func WithExtension ¶
WithExtension adds a specification extension to the root OpenAPI specification.
Extension keys MUST start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved for the OpenAPI Initiative.
The value can be any valid JSON value (null, primitive, array, or object). Validation of extension keys happens during API.Validate().
Example:
openapi.WithExtension("x-internal-id", "api-v2")
openapi.WithExtension("x-code-samples", []map[string]any{
{"lang": "curl", "source": "curl https://api.example.com/users"},
})
func WithExternalDocs ¶
WithExternalDocs sets external documentation URL and optional description.
func WithInfoDescription ¶
WithInfoDescription sets the API description in the Info object.
The description supports Markdown formatting and appears in the OpenAPI spec and Swagger UI.
Example:
openapi.WithInfoDescription("A RESTful API for managing users and their profiles.")
func WithInfoExtension ¶
WithInfoExtension adds a specification extension to the Info object.
Extension keys must start with "x-". In OpenAPI 3.1.x, keys starting with "x-oai-" or "x-oas-" are reserved and cannot be used.
Example:
openapi.WithInfoExtension("x-api-category", "public")
func WithInfoSummary ¶
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 WithInfoTitle ¶
WithInfoTitle sets the API title.
Example:
openapi.WithInfoTitle("User Management API")
func WithInfoVersion ¶
WithInfoVersion sets the API version.
Example:
openapi.WithInfoVersion("2.1.0")
func WithLicense ¶
WithLicense sets license information for the API using a URL (OpenAPI 3.0 style).
The name is required. URL is optional. This is mutually exclusive with identifier - use WithLicenseIdentifier for SPDX identifiers. Validation occurs when New() is called.
Example:
openapi.WithLicense("MIT", "https://opensource.org/licenses/MIT")
func WithLicenseIdentifier ¶
WithLicenseIdentifier sets license information for the API using an SPDX identifier (OpenAPI 3.1+).
The name is required. Identifier is an SPDX license expression (e.g., "Apache-2.0"). This is mutually exclusive with URL - use WithLicense for URL-based licenses. Validation occurs when New() is called.
Example:
openapi.WithLicenseIdentifier("Apache 2.0", "Apache-2.0")
func WithOAuth2 ¶
func WithOAuth2(name, desc string, flows ...OAuth2Flow) Option
WithOAuth2 adds OAuth2 authentication scheme.
At least one flow must be configured. Use OAuth2Flow to configure each flow type. Multiple flows can be provided to support different OAuth2 flow types.
Example:
openapi.WithOAuth2("oauth2", "OAuth2 authentication",
openapi.OAuth2Flow{
Type: openapi.FlowAuthorizationCode,
AuthorizationURL: "https://example.com/oauth/authorize",
TokenURL: "https://example.com/oauth/token",
Scopes: map[string]string{
"read": "Read access",
"write": "Write access",
},
},
openapi.OAuth2Flow{
Type: openapi.FlowClientCredentials,
TokenUrl: "https://example.com/oauth/token",
Scopes: map[string]string{"read": "Read access"},
},
)
func WithOpenIDConnect ¶
WithOpenIDConnect adds OpenID Connect authentication scheme.
Parameters:
- name: Scheme name used in security requirements
- url: Well-known URL to discover OpenID Connect provider metadata
- desc: Description shown in Swagger UI
Example:
openapi.WithOpenIDConnect("oidc", "https://example.com/.well-known/openid-configuration", "OpenID Connect authentication")
func WithSchemaPrefix ¶
WithSchemaPrefix sets the prefix for OpenAPI schema references. The prefix is used when generating $ref references to schemas in components/schemas.
Default: "#/components/schemas/"
Example:
openapi.WithSchemaPrefix("#/definitions/")
func WithServer ¶
func WithServer(url string, opts ...ServerOption) Option
WithServer adds a server URL to the specification.
Multiple servers can be added by calling this option multiple times. Use server options to configure description, variables, and extensions.
Example:
openapi.WithServer("https://api.example.com",
openapi.WithServerDescription("Production"),
),
openapi.WithServer("https://{env}.example.com",
openapi.WithServerDescription("Multi-tenant API"),
openapi.WithServerVariable("env", "prod", []string{"prod", "staging"}, "Environment"),
openapi.WithServerExtension("x-region", "us-east-1"),
),
func WithStrictDownlevel ¶
WithStrictDownlevel causes projection to error (instead of warn) when 3.1-only features are used with a 3.0 target.
Default: false (warnings only)
Example:
openapi.WithStrictDownlevel(true)
func WithTag ¶
WithTag adds a tag to the specification.
Tags are used to group operations in Swagger UI. Operations can be assigned tags using RouteWrapper.Tags(). Multiple tags can be added by calling this option multiple times.
Example:
openapi.WithTag("users", "User management operations"),
openapi.WithTag("orders", "Order processing operations"),
func WithTagConfig ¶
WithTagConfig configures struct tag names used for OpenAPI schema generation.
By default, the following tag names are used:
- schema: for parameter location/style metadata
- body: for request/response body metadata
- openapi: for OpenAPI-specific metadata
- validate: for validation constraints
- default: for default values
- requires: for dependent required fields
Use this option to customize tag names for compatibility with other libraries or to match your existing codebase conventions.
Partial configurations are supported - only provide the tag names you want to customize. Unspecified tags will use their defaults.
Example:
import "github.com/talav/openapi/config"
// Customize only specific tags - others use defaults
openapi.NewAPI(
openapi.WithTagConfig(config.TagConfig{
Schema: "param", // Custom
OpenAPI: "api", // Custom
Validate: "rules", // Custom
// Body, Default, Requires will use defaults ("body", "default", "requires")
}),
)
func WithTermsOfService ¶
WithTermsOfService sets the Terms of Service URL/URI.
func WithValidation ¶
WithValidation enables or disables JSON Schema validation of the generated OpenAPI spec.
When enabled, Generate() validates the output against the official OpenAPI meta-schema and returns an error if the spec is invalid.
This is useful for:
- Development: Catch spec generation bugs early
- CI/CD: Ensure generated specs are valid before deployment
- Testing: Verify spec correctness in tests
Performance: Adds ~1-5ms overhead per generation. The default is false for backward compatibility. Enable for development and testing to catch errors early.
Default: false
Example:
openapi.WithValidation(false) // Disable for performance
func WithVersion ¶
WithVersion sets the target OpenAPI version.
Example:
openapi.WithVersion("3.1.2")
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 SecurityReq ¶
SecurityReq represents a security requirement for an operation.
type ServerOption ¶
ServerOption configures a Server using the functional options pattern.
func WithServerDescription ¶
func WithServerDescription(desc string) ServerOption
WithServerDescription sets the server description.
Example:
openapi.WithServer("https://api.example.com",
openapi.WithServerDescription("Production environment"),
),
func WithServerExtension ¶
func WithServerExtension(key string, value any) ServerOption
WithServerExtension adds a specification extension to the server.
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.WithServer("https://api.example.com",
openapi.WithServerExtension("x-region", "us-east-1"),
openapi.WithServerExtension("x-deployment", "production"),
),
func WithServerVariable ¶
func WithServerVariable(name, defaultValue string, enum []string, description string) ServerOption
WithServerVariable adds a variable to the server URL template.
The variable name should match a placeholder in the server URL (e.g., {username}). Default is required. Enum and description are optional.
Example:
openapi.WithServer("https://{username}.example.com:{port}/v1",
openapi.WithServerVariable("username", "demo", []string{"demo", "prod"}, "User subdomain"),
openapi.WithServerVariable("port", "8443", []string{"8443", "443"}, "Server port"),
),
Directories
¶
| Path | Synopsis |
|---|---|
|
Package example provides OpenAPI Example Object support.
|
Package example provides OpenAPI Example Object support. |
|
internal
|
|
|
metadata
Package metadata extracts OpenAPI schema metadata from Go struct field tags.
|
Package metadata extracts OpenAPI schema metadata from Go struct field tags. |