Documentation
¶
Overview ¶
Package builder provides programmatic construction of OpenAPI Specification documents.
The builder package enables users to construct OAS documents in Go using a fluent API with automatic reflection-based schema generation. Go types are passed directly to the API, and the builder automatically generates OpenAPI-compatible JSON schemas.
Supported Versions ¶
The builder supports both OAS 2.0 (Swagger) and OAS 3.x (3.0.0 through 3.2.0). Use New() with the desired OAS version and the corresponding Build method:
- New(parser.OASVersion20) + BuildOAS2() → *parser.OAS2Document with schemas in "definitions"
- New(parser.OASVersion3xx) + BuildOAS3() → *parser.OAS3Document with schemas in "components/schemas"
The $ref paths are automatically adjusted based on the OAS version:
- OAS 2.0: "#/definitions/", "#/parameters/", "#/responses/"
- OAS 3.x: "#/components/schemas/", "#/components/parameters/", "#/components/responses/"
Validation ¶
The builder does not perform OAS specification validation. Use the validator package to validate built documents:
result, _ := spec.BuildResult() valResult, _ := validator.ValidateWithOptions(validator.WithParsed(*result))
Quick Start ¶
Build an OAS 3.x API specification:
spec := builder.New(parser.OASVersion320).
SetTitle("My API").
SetVersion("1.0.0")
spec.AddOperation(http.MethodGet, "/users",
builder.WithOperationID("listUsers"),
builder.WithResponse(http.StatusOK, []User{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
// doc is *parser.OAS3Document - no type assertion needed
Build an OAS 2.0 (Swagger) API specification:
spec := builder.New(parser.OASVersion20).
SetTitle("My API").
SetVersion("1.0.0")
spec.AddOperation(http.MethodGet, "/users",
builder.WithOperationID("listUsers"),
builder.WithResponse(http.StatusOK, []User{}),
)
doc, err := spec.BuildOAS2()
if err != nil {
log.Fatal(err)
}
// doc is *parser.OAS2Document - no type assertion needed
Modifying Existing Documents ¶
Use FromDocument or FromOAS2Document to create a builder from an existing document:
// For OAS 3.x documents b := builder.FromDocument(existingOAS3Doc) b.AddOperation(http.MethodPost, "/users", ...) newDoc, _ := b.BuildOAS3() // For OAS 2.0 documents b := builder.FromOAS2Document(existingSwaggerDoc) b.AddOperation(http.MethodPost, "/users", ...) newDoc, _ := b.BuildOAS2()
Webhooks (OAS 3.1+) ¶
For OAS 3.1+ specifications, webhooks can be added using AddWebhook:
spec := builder.New(parser.OASVersion310).
SetTitle("Webhook API").
SetVersion("1.0.0").
AddWebhook("userCreated", http.MethodPost,
builder.WithRequestBody("application/json", UserEvent{}),
builder.WithResponse(http.StatusOK, struct{}{}),
)
External Documentation ¶
Add document-level external documentation using SetExternalDocs:
spec := builder.New(parser.OASVersion320).
SetTitle("My API").
SetVersion("1.0.0").
SetExternalDocs(&parser.ExternalDocs{
URL: "https://docs.example.com",
Description: "API documentation",
})
Reflection-Based Schema Generation ¶
The core feature is automatic schema generation from Go types via reflection. When you pass a Go type to WithResponse, WithRequestBody, or parameter options, the builder inspects the type structure and generates an OpenAPI-compatible schema.
Type mappings:
- string → string
- int, int32 → integer (format: int32)
- int64 → integer (format: int64)
- float32 → number (format: float)
- float64 → number (format: double)
- bool → boolean
- []T → array (items from T)
- map[string]T → object (additionalProperties from T)
- struct → object (properties from fields)
- *T → schema of T (nullable)
- time.Time → string (format: date-time)
Schema Naming ¶
Schemas are named using the Go convention of "package.TypeName" (e.g., "models.User"). This ensures uniqueness and matches Go developers' expectations for type identification. If multiple packages have the same base name (e.g., github.com/foo/models and github.com/bar/models), the full package path is used to disambiguate (e.g., "github.com_foo_models.User"). Anonymous types are named "AnonymousType".
Extensible Schema Naming ¶
The default schema naming uses "package.TypeName" format. For custom naming, use options when creating a Builder:
Built-in strategies:
// PascalCase: ModelsUser
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNaming(builder.SchemaNamingPascalCase),
)
// Type only (no package prefix): User
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNaming(builder.SchemaNamingTypeOnly),
)
Available strategies:
- SchemaNamingDefault: "package.TypeName" (e.g., models.User)
- SchemaNamingPascalCase: "PackageTypeName" (e.g., ModelsUser)
- SchemaNamingCamelCase: "packageTypeName" (e.g., modelsUser)
- SchemaNamingSnakeCase: "package_type_name" (e.g., models_user)
- SchemaNamingKebabCase: "package-type-name" (e.g., models-user)
- SchemaNamingTypeOnly: "TypeName" (e.g., User) - may cause conflicts
- SchemaNamingFullPath: "full_path_TypeName" (e.g., github.com_org_models_User)
Custom templates using Go text/template:
// Custom format: models+User
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNameTemplate(`{{.Package}}+{{.Type}}`),
)
Available template functions: pascal, camel, snake, kebab, upper, lower, title, sanitize, trimPrefix, trimSuffix, replace, join.
Custom naming function for maximum flexibility:
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNameFunc(func(ctx builder.SchemaNameContext) string {
return strings.ToUpper(ctx.Type)
}),
)
Note: RegisterTypeAs always takes precedence over any naming strategy.
Generic Types ¶
Go 1.18+ generic types are fully supported. The type parameters are included in the schema name but sanitized for URI safety by replacing brackets with underscores:
Response[User] → "builder.Response_User" Map[string,int] → "builder.Map_string_int" Response[List[User]] → "builder.Response_List_User"
This ensures $ref URIs are valid and compatible with all OpenAPI tools, which may not handle square brackets properly in schema references.
Generic type naming strategies control how generic types are formatted:
// "Of" separator: Response[User] → ResponseOfUser
spec := builder.New(parser.OASVersion320,
builder.WithGenericNaming(builder.GenericNamingOf),
)
Available generic strategies:
- GenericNamingUnderscore: "Response_User_" (default)
- GenericNamingOf: "ResponseOfUser"
- GenericNamingFor: "ResponseForUser"
- GenericNamingAngleBrackets: "Response<User>" (URI-encoded in $ref)
- GenericNamingFlattened: "ResponseUser"
For fine-grained control over generic naming:
spec := builder.New(parser.OASVersion320,
builder.WithGenericNamingConfig(builder.GenericNamingConfig{
Strategy: builder.GenericNamingOf,
ParamSeparator: "And",
ApplyBaseCasing: true,
}),
)
Struct Tags ¶
Customize schema generation with struct tags:
type User struct {
ID int64 `json:"id" oas:"description=Unique identifier"`
Name string `json:"name" oas:"minLength=1,maxLength=100"`
Email string `json:"email" oas:"format=email"`
Role string `json:"role" oas:"enum=admin|user|guest"`
}
Supported oas tag options:
- description=<text> - Field description
- format=<format> - Override format (email, uri, uuid, date, date-time, etc.)
- enum=<val1>|<val2>|... - Enumeration values
- minimum=<n>, maximum=<n> - Numeric constraints
- minLength=<n>, maxLength=<n> - String length constraints
- pattern=<regex> - String pattern
- minItems=<n>, maxItems=<n> - Array constraints
- readOnly=true, writeOnly=true - Access modifiers
- nullable=true - Explicitly nullable
- deprecated=true - Mark as deprecated
Required Fields ¶
Required fields are determined by:
- Non-pointer fields without omitempty are required
- Fields with oas:"required=true" are explicitly required
- Fields with oas:"required=false" are explicitly optional
Operation Responses ¶
Note: OpenAPI requires at least one response per operation. If no responses are defined, the resulting spec will fail OAS validation. Always use WithResponse() or WithDefaultResponse() to add responses to operations.
Parameter Constraints ¶
Add validation constraints to parameters using WithParam* options:
spec.AddOperation(http.MethodGet, "/pets",
builder.WithQueryParam("limit", int32(0),
builder.WithParamDescription("Maximum number of pets to return"),
builder.WithParamMinimum(1),
builder.WithParamMaximum(100),
builder.WithParamDefault(20),
),
builder.WithQueryParam("status", string(""),
builder.WithParamEnum("available", "pending", "sold"),
),
builder.WithQueryParam("name", string(""),
builder.WithParamMinLength(1),
builder.WithParamMaxLength(50),
builder.WithParamPattern("^[a-zA-Z]+$"),
),
)
Supported parameter constraint options:
- WithParamMinimum(min float64) - Minimum value for numeric parameters
- WithParamMaximum(max float64) - Maximum value for numeric parameters
- WithParamExclusiveMinimum(exclusive bool) - Whether minimum is exclusive
- WithParamExclusiveMaximum(exclusive bool) - Whether maximum is exclusive
- WithParamMultipleOf(value float64) - Value must be a multiple of this (must be > 0)
- WithParamMinLength(min int) - Minimum length for string parameters (must be >= 0)
- WithParamMaxLength(max int) - Maximum length for string parameters (must be >= 0)
- WithParamPattern(pattern string) - Regex pattern for string parameters (validated at build time)
- WithParamMinItems(min int) - Minimum items for array parameters (must be >= 0)
- WithParamMaxItems(max int) - Maximum items for array parameters (must be >= 0)
- WithParamUniqueItems(unique bool) - Whether array items must be unique
- WithParamEnum(values ...any) - Allowed enumeration values
- WithParamDefault(value any) - Default value for the parameter
Explicit Type and Format Overrides ¶
Override the inferred OpenAPI type or format when the Go type doesn't map directly to your desired schema:
spec.AddOperation(http.MethodGet, "/users/{user_id}",
builder.WithPathParam("user_id", "",
builder.WithParamFormat("uuid"),
),
builder.WithQueryParam("version", 0,
builder.WithParamType("integer"),
builder.WithParamFormat("int64"),
),
)
Available type/format override options:
- WithParamType(typeName string) - Override inferred type (string, integer, number, boolean, array, object)
- WithParamFormat(format string) - Override inferred format (uuid, email, date-time, byte, binary, etc.)
- WithParamSchema(schema *parser.Schema) - Full schema override (highest precedence)
Precedence rules:
- WithParamSchema takes highest precedence (complete replacement)
- WithParamType replaces the inferred type
- WithParamFormat replaces the inferred format
Constraint validation is performed when building the document. The following rules are enforced:
- minimum must be <= maximum (if both are set)
- minLength must be <= maxLength (if both are set)
- minItems must be <= maxItems (if both are set)
- minLength, maxLength, minItems, maxItems must be non-negative
- multipleOf must be greater than 0
- pattern must be a valid regex
Form Parameters ¶
Form parameters are handled differently across OAS versions. The builder provides a unified WithFormParam method that automatically adapts to the target OAS version:
spec.AddOperation(http.MethodPost, "/login",
builder.WithFormParam("username", string(""),
builder.WithParamRequired(true),
builder.WithParamMinLength(3),
),
builder.WithFormParam("password", string(""),
builder.WithParamRequired(true),
builder.WithParamMinLength(8),
),
builder.WithResponse(http.StatusOK, LoginResponse{}),
)
OAS 2.0: Form parameters are created as parameters with in="formData":
parameters:
- name: username
in: formData
type: string
required: true
minLength: 3
OAS 3.x: Form parameters are added to the request body with application/x-www-form-urlencoded:
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
username:
type: string
minLength: 3
required:
- username
All parameter constraints and options work with form parameters. If a request body already exists (e.g., for multipart/form-data), form parameters are merged into it with the application/x-www-form-urlencoded content type.
OAS Version Differences for Constraints ¶
The builder handles constraint placement automatically based on the OAS version:
OAS 3.x (3.0.0+): Constraints are applied to the parameter's Schema field. The OAS 3.x specification separates the parameter metadata (name, location, required) from the value schema (type, format, constraints). This is the modern approach:
parameters:
- name: limit
in: query
schema:
type: integer
minimum: 1 # Constraint on schema
maximum: 100 # Constraint on schema
OAS 2.0 (Swagger): Constraints are applied directly to the Parameter object. In OAS 2.0, non-body parameters have type and constraints as top-level fields:
parameters:
- name: limit
in: query
type: integer
minimum: 1 # Constraint on parameter
maximum: 100 # Constraint on parameter
The builder abstracts this difference, allowing you to use the same WithParam* options regardless of target OAS version.
Custom Content Types ¶
Use WithResponseContentType to specify content types other than the default "application/json":
spec.AddOperation(http.MethodGet, "/users",
builder.WithResponse(http.StatusOK, []User{},
builder.WithResponseContentType("application/xml"),
),
)
For multiple content types, use WithRequestBodyContentTypes or WithResponseContentTypes:
spec.AddOperation(http.MethodPost, "/users",
builder.WithRequestBodyContentTypes(
[]string{"application/json", "application/xml"},
User{},
),
builder.WithResponseContentTypes(http.StatusOK,
[]string{"application/json", "application/xml"},
User{},
),
)
Vendor Extensions ¶
Add vendor extensions (x-* fields) to operations, parameters, responses, and request bodies:
spec.AddOperation(http.MethodGet, "/users",
builder.WithOperationExtension("x-rate-limit", 100),
builder.WithQueryParam("limit", int32(0),
builder.WithParamExtension("x-ui-widget", "slider"),
),
builder.WithResponse(http.StatusOK, []User{},
builder.WithResponseExtension("x-cache-ttl", 3600),
),
)
spec.AddOperation(http.MethodPost, "/users",
builder.WithRequestBody("application/json", User{},
builder.WithRequestBodyExtension("x-codegen-request-body-name", "user"),
),
)
OAS 2.0 Specific Options ¶
For OAS 2.0 specifications, additional options are available:
spec.AddOperation(http.MethodPost, "/users",
builder.WithConsumes("application/json", "application/xml"),
builder.WithProduces("application/json"),
builder.WithQueryParam("tags", []string{},
builder.WithParamCollectionFormat("csv"), // csv, ssv, tsv, pipes, multi
builder.WithParamAllowEmptyValue(true),
),
)
See the examples in example_test.go for more patterns.
Semantic Schema Deduplication ¶
The builder can automatically identify and consolidate structurally identical schemas, reducing document size when multiple types converge to the same structure.
Enable via option:
spec := builder.New(parser.OASVersion320,
builder.WithSemanticDeduplication(true),
)
// Add schemas that happen to be structurally identical
spec.AddOperation(http.MethodGet, "/addresses",
builder.WithResponse(http.StatusOK, []Address{}),
)
spec.AddOperation(http.MethodGet, "/locations",
builder.WithResponse(http.StatusOK, []Location{}), // Same structure as Address
)
doc, _ := spec.BuildOAS3()
// Only one schema exists; all $refs point to the canonical (alphabetically first) name
Or call manually before building:
spec.DeduplicateSchemas() doc, _ := spec.BuildOAS3()
Deduplication compares schemas structurally, ignoring metadata fields (title, description, example, deprecated). When duplicates are found, the alphabetically first name becomes canonical, and all references are automatically rewritten.
Related Packages ¶
The builder integrates with other oastools packages:
- github.com/erraggy/oastools/parser - Builder generates parser-compatible documents
- github.com/erraggy/oastools/validator - Validate built specifications
- github.com/erraggy/oastools/fixer - Fix common validation errors in built specifications
- github.com/erraggy/oastools/converter - Convert built specs between OAS versions
- github.com/erraggy/oastools/joiner - Join built specs with existing documents
- github.com/erraggy/oastools/differ - Compare built specs with other specifications
- github.com/erraggy/oastools/generator - Generate code from built specifications
Example ¶
Example demonstrates basic builder usage.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Pet represents a pet in the store.
type Pet struct {
ID int64 `json:"id" oas:"description=Unique pet identifier"`
Name string `json:"name" oas:"minLength=1,description=Pet name"`
Tag string `json:"tag,omitempty" oas:"description=Optional tag"`
CreatedAt time.Time `json:"created_at" oas:"readOnly=true"`
}
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("Pet Store API").
SetVersion("1.0.0")
spec.AddOperation(http.MethodGet, "/pets",
builder.WithOperationID("listPets"),
builder.WithResponse(http.StatusOK, []Pet{}),
)
// Use BuildOAS3() for type-safe access - no type assertion needed
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
fmt.Printf("OpenAPI: %s\n", doc.OpenAPI)
fmt.Printf("Title: %s\n", doc.Info.Title)
fmt.Printf("Paths: %d\n", len(doc.Paths))
}
Output: OpenAPI: 3.2.0 Title: Pet Store API Paths: 1
Example (CompleteAPI) ¶
Example_completeAPI demonstrates a complete API specification.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Pet represents a pet in the store.
type Pet struct {
ID int64 `json:"id" oas:"description=Unique pet identifier"`
Name string `json:"name" oas:"minLength=1,description=Pet name"`
Tag string `json:"tag,omitempty" oas:"description=Optional tag"`
CreatedAt time.Time `json:"created_at" oas:"readOnly=true"`
}
// Error represents an API error.
type Error struct {
Code int32 `json:"code" oas:"description=Error code"`
Message string `json:"message" oas:"description=Error message"`
}
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("Pet Store API").
SetVersion("1.0.0").
SetDescription("A sample Pet Store API demonstrating the builder package").
AddServer("https://api.petstore.example.com/v1",
builder.WithServerDescription("Production server"),
).
AddTag("pets", builder.WithTagDescription("Operations about pets")).
AddAPIKeySecurityScheme("api_key", "header", "X-API-Key", "API key").
SetSecurity(builder.SecurityRequirement("api_key"))
// List pets
spec.AddOperation(http.MethodGet, "/pets",
builder.WithOperationID("listPets"),
builder.WithSummary("List all pets"),
builder.WithTags("pets"),
builder.WithQueryParam("limit", int32(0),
builder.WithParamDescription("Maximum number of pets to return"),
),
builder.WithResponse(http.StatusOK, []Pet{},
builder.WithResponseDescription("A list of pets"),
),
builder.WithResponse(http.StatusInternalServerError, Error{},
builder.WithResponseDescription("Unexpected error"),
),
)
// Get pet by ID
spec.AddOperation(http.MethodGet, "/pets/{petId}",
builder.WithOperationID("getPet"),
builder.WithSummary("Get a pet by ID"),
builder.WithTags("pets"),
builder.WithPathParam("petId", int64(0),
builder.WithParamDescription("The ID of the pet to retrieve"),
),
builder.WithResponse(http.StatusOK, Pet{},
builder.WithResponseDescription("The requested pet"),
),
builder.WithResponse(http.StatusNotFound, Error{},
builder.WithResponseDescription("Pet not found"),
),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Title: %s\n", doc.Info.Title)
fmt.Printf("Paths: %d\n", len(doc.Paths))
fmt.Printf("Tags: %d\n", len(doc.Tags))
fmt.Printf("Schemas: %d\n", len(doc.Components.Schemas))
}
Output: Title: Pet Store API Paths: 2 Tags: 1 Schemas: 2
Example (FromDocument) ¶
Example_fromDocument demonstrates modifying an existing document.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
// Create an existing document (in real code, this would be parsed from a file)
existingDoc := &parser.OAS3Document{
OpenAPI: "3.0.3",
Info: &parser.Info{
Title: "Existing API",
Version: "1.0.0",
},
Paths: parser.Paths{
"/existing": &parser.PathItem{
Get: &parser.Operation{
OperationID: "existingOperation",
Responses: &parser.Responses{
Codes: map[string]*parser.Response{
"200": {
Description: "Existing response",
},
},
},
},
},
},
}
// Create builder from existing document and add new operations
spec := builder.FromDocument(existingDoc)
type HealthResponse struct {
Status string `json:"status"`
}
spec.AddOperation(http.MethodGet, "/health",
builder.WithOperationID("healthCheck"),
builder.WithResponse(http.StatusOK, HealthResponse{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Paths: %d\n", len(doc.Paths))
fmt.Printf("Has /existing: %v\n", doc.Paths["/existing"] != nil)
fmt.Printf("Has /health: %v\n", doc.Paths["/health"] != nil)
}
Output: Paths: 2 Has /existing: true Has /health: true
Example (GenericNamingConfig) ¶
Example_genericNamingConfig demonstrates fine-grained generic type naming configuration. Use WithGenericNamingConfig for full control over how generic type parameters are formatted.
package main
import (
"fmt"
"net/http"
"time"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Pet represents a pet in the store.
type Pet struct {
ID int64 `json:"id" oas:"description=Unique pet identifier"`
Name string `json:"name" oas:"minLength=1,description=Pet name"`
Tag string `json:"tag,omitempty" oas:"description=Optional tag"`
CreatedAt time.Time `json:"created_at" oas:"readOnly=true"`
}
func main() {
// Configure generic naming with custom settings.
// This example uses GenericNamingOf strategy with "And" as the separator
// between multiple type parameters.
//
// For generic types like Response[User], this would produce "ResponseOfUser".
// For types like Map[string,int], this would produce "MapOfStringAndOfInt".
spec := builder.New(parser.OASVersion320,
builder.WithGenericNamingConfig(builder.GenericNamingConfig{
Strategy: builder.GenericNamingOf,
ParamSeparator: "And",
ApplyBaseCasing: true,
}),
).
SetTitle("Example API").
SetVersion("1.0.0").
AddOperation(http.MethodGet, "/pets",
builder.WithResponse(http.StatusOK, []Pet{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Title: %s\n", doc.Info.Title)
fmt.Printf("Schemas: %d\n", len(doc.Components.Schemas))
}
Output: Title: Example API Schemas: 1
Example (SchemaGeneration) ¶
Example_schemaGeneration demonstrates automatic schema generation.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Country string `json:"country"`
}
type Customer struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email" oas:"format=email"`
Address Address `json:"address"`
}
spec := builder.New(parser.OASVersion320).
SetTitle("Customer API").
SetVersion("1.0.0").
AddOperation(http.MethodGet, "/customers/{id}",
builder.WithOperationID("getCustomer"),
builder.WithPathParam("id", int64(0)),
builder.WithResponse(http.StatusOK, Customer{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
// Both Customer and Address schemas are auto-generated with package-qualified names
_, hasCustomer := doc.Components.Schemas["builder_test.Customer"]
_, hasAddress := doc.Components.Schemas["builder_test.Address"]
fmt.Printf("Has Customer schema: %v\n", hasCustomer)
fmt.Printf("Has Address schema: %v\n", hasAddress)
}
Output: Has Customer schema: true Has Address schema: true
Example (SchemaNamingCustomFunc) ¶
Example_schemaNamingCustomFunc demonstrates custom function-based schema naming. Use WithSchemaNameFunc for maximum flexibility when you need programmatic control over schema names based on type metadata.
package main
import (
"fmt"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
type Order struct {
ID int64 `json:"id"`
Total float64 `json:"total"`
Status string `json:"status"`
}
// Custom naming function that prefixes schemas with API version
// and converts the type name to uppercase
apiVersion := "V2"
customNamer := func(ctx builder.SchemaNameContext) string {
// Use the type name, converting to uppercase for emphasis
return apiVersion + "_" + ctx.Type
}
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNameFunc(customNamer),
).
SetTitle("Order API").
SetVersion("2.0.0").
AddOperation(http.MethodGet, "/orders",
builder.WithResponse(http.StatusOK, Order{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
fmt.Println("Error:", err)
return
}
// Print schema names
for name := range doc.Components.Schemas {
fmt.Println("Schema:", name)
}
}
Output: Schema: V2_Order
Example (SchemaNamingPascalCase) ¶
Example_schemaNamingPascalCase demonstrates PascalCase schema naming strategy. With SchemaNamingPascalCase, "package.TypeName" becomes "PackageTypeName".
package main
import (
"fmt"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNaming(builder.SchemaNamingPascalCase),
).
SetTitle("Example API").
SetVersion("1.0.0").
AddOperation(http.MethodGet, "/users",
builder.WithResponse(http.StatusOK, User{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
fmt.Println("Error:", err)
return
}
// Print schema names
for name := range doc.Components.Schemas {
fmt.Println("Schema:", name)
}
}
Output: Schema: BuilderTestUser
Example (SchemaNamingTemplate) ¶
Example_schemaNamingTemplate demonstrates custom template-based schema naming. Templates use Go text/template syntax with helper functions like pascal, camel, etc.
package main
import (
"fmt"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
type Product struct {
ID int `json:"id"`
Price float64 `json:"price"`
}
// Custom template: prefix with "API" and use pascal case
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNameTemplate(`API{{pascal .Type}}`),
).
SetTitle("Example API").
SetVersion("1.0.0").
AddOperation(http.MethodGet, "/products",
builder.WithResponse(http.StatusOK, Product{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
fmt.Println("Error:", err)
return
}
// Print schema names
for name := range doc.Components.Schemas {
fmt.Println("Schema:", name)
}
}
Output: Schema: APIProduct
Example (SemanticDeduplication) ¶
Example_semanticDeduplication demonstrates automatic consolidation of identical schemas. When multiple Go types generate structurally identical schemas, enabling semantic deduplication identifies these duplicates and consolidates them to a single canonical schema.
package main
import (
"fmt"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
// Define types that are structurally identical but have different names
type UserID struct {
Value int64 `json:"value"`
}
type CustomerID struct {
Value int64 `json:"value"`
}
type OrderID struct {
Value int64 `json:"value"`
}
// Build specification with semantic deduplication enabled
spec := builder.New(parser.OASVersion320,
builder.WithSemanticDeduplication(true),
).
SetTitle("ID API").
SetVersion("1.0.0").
AddOperation(http.MethodGet, "/users/{id}",
builder.WithResponse(http.StatusOK, UserID{}),
).
AddOperation(http.MethodGet, "/customers/{id}",
builder.WithResponse(http.StatusOK, CustomerID{}),
).
AddOperation(http.MethodGet, "/orders/{id}",
builder.WithResponse(http.StatusOK, OrderID{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
fmt.Println("Error:", err)
return
}
// Without deduplication: 3 schemas (UserID, CustomerID, OrderID)
// With deduplication: 1 schema (the alphabetically first canonical name)
fmt.Printf("Title: %s\n", doc.Info.Title)
fmt.Printf("Schemas: %d\n", len(doc.Components.Schemas))
fmt.Printf("Operations: %d\n", len(doc.Paths))
}
Output: Title: ID API Schemas: 1 Operations: 3
Example (WithComplexRawSchema) ¶
Example_withComplexRawSchema demonstrates using raw schemas for complex multipart uploads.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("Complex Upload API").
SetVersion("1.0.0")
// Complex multipart schema with file and metadata
uploadSchema := &parser.Schema{
Type: "object",
Properties: map[string]*parser.Schema{
"file": {
Type: "string",
Format: "binary",
Description: "The file data",
},
"metadata": {
Type: "object",
Properties: map[string]*parser.Schema{
"filename": {
Type: "string",
Description: "Original filename",
},
"tags": {
Type: "array",
Items: &parser.Schema{Type: "string"},
Description: "File tags",
},
},
},
},
Required: []string{"file"},
}
spec.AddOperation(http.MethodPost, "/upload-with-metadata",
builder.WithOperationID("uploadWithMetadata"),
builder.WithRequestBodyRawSchema("multipart/form-data", uploadSchema,
builder.WithRequired(true),
builder.WithRequestDescription("Upload file with metadata"),
),
builder.WithResponse(http.StatusCreated, struct {
ID string `json:"id"`
}{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
rb := doc.Paths["/upload-with-metadata"].Post.RequestBody
schema := rb.Content["multipart/form-data"].Schema
fmt.Printf("Request body required: %v\n", rb.Required)
fmt.Printf("Has file property: %v\n", schema.Properties["file"] != nil)
fmt.Printf("Has metadata property: %v\n", schema.Properties["metadata"] != nil)
fmt.Printf("File format: %s\n", schema.Properties["file"].Format)
fmt.Printf("Required fields: %v\n", schema.Required)
}
Output: Request body required: true Has file property: true Has metadata property: true File format: binary Required fields: [file]
Example (WithFileUpload) ¶
Example_withFileUpload demonstrates file upload support using WithFileParam.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
// OAS 3.x file upload with multipart/form-data
spec := builder.New(parser.OASVersion320).
SetTitle("File Upload API").
SetVersion("1.0.0")
spec.AddOperation(http.MethodPost, "/upload",
builder.WithOperationID("uploadFile"),
builder.WithFileParam("file",
builder.WithParamRequired(true),
builder.WithParamDescription("File to upload"),
),
builder.WithFormParam("description", "",
builder.WithParamDescription("File description"),
),
builder.WithResponse(http.StatusOK, struct {
Success bool `json:"success"`
FileID string `json:"file_id"`
}{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
rb := doc.Paths["/upload"].Post.RequestBody
schema := rb.Content["multipart/form-data"].Schema
fmt.Printf("Has file property: %v\n", schema.Properties["file"] != nil)
fmt.Printf("File type: %s\n", schema.Properties["file"].Type)
fmt.Printf("File format: %s\n", schema.Properties["file"].Format)
fmt.Printf("Has description: %v\n", schema.Properties["description"] != nil)
fmt.Printf("Required: %v\n", schema.Required)
}
Output: Has file property: true File type: string File format: binary Has description: true Required: [file]
Example (WithFormParameters) ¶
Example_withFormParameters demonstrates using form parameters. Form parameters work differently in OAS 2.0 vs 3.x:
- OAS 2.0: parameters with in="formData"
- OAS 3.x: request body with application/x-www-form-urlencoded
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Error represents an API error.
type Error struct {
Code int32 `json:"code" oas:"description=Error code"`
Message string `json:"message" oas:"description=Error message"`
}
func main() {
// OAS 3.x example - form parameters become request body
spec := builder.New(parser.OASVersion320).
SetTitle("Login API").
SetVersion("1.0.0")
type LoginResponse struct {
Token string `json:"token"`
ExpiresIn int32 `json:"expires_in"`
}
spec.AddOperation(http.MethodPost, "/login",
builder.WithOperationID("login"),
builder.WithSummary("User login"),
// Form parameters are automatically converted to request body schema
builder.WithFormParam("username", "",
builder.WithParamDescription("User's username"),
builder.WithParamRequired(true),
builder.WithParamMinLength(3),
builder.WithParamMaxLength(20),
),
builder.WithFormParam("password", "",
builder.WithParamDescription("User's password"),
builder.WithParamRequired(true),
builder.WithParamMinLength(8),
),
builder.WithFormParam("remember_me", false,
builder.WithParamDescription("Remember login session"),
builder.WithParamDefault(false),
),
builder.WithResponse(http.StatusOK, LoginResponse{},
builder.WithResponseDescription("Successful login"),
),
builder.WithResponse(http.StatusUnauthorized, Error{},
builder.WithResponseDescription("Invalid credentials"),
),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
// Form parameters are in the request body
rb := doc.Paths["/login"].Post.RequestBody
mediaType := rb.Content["application/x-www-form-urlencoded"]
fmt.Printf("Request body content type: application/x-www-form-urlencoded\n")
fmt.Printf("Form fields: %d\n", len(mediaType.Schema.Properties))
fmt.Printf("Required fields: %d\n", len(mediaType.Schema.Required))
fmt.Printf("Has username: %v\n", mediaType.Schema.Properties["username"] != nil)
fmt.Printf("Has password: %v\n", mediaType.Schema.Properties["password"] != nil)
fmt.Printf("Has remember_me: %v\n", mediaType.Schema.Properties["remember_me"] != nil)
}
Output: Request body content type: application/x-www-form-urlencoded Form fields: 3 Required fields: 2 Has username: true Has password: true Has remember_me: true
Example (WithParamTypeFormatOverride) ¶
Example_withParamTypeFormatOverride demonstrates explicit type and format overrides. Use WithParamType and WithParamFormat when the Go type doesn't map directly to the desired OpenAPI type/format, such as using a string for UUID identifiers or representing binary data as base64.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("ID API").
SetVersion("1.0.0")
spec.AddOperation(http.MethodGet, "/users/{user_id}",
builder.WithOperationID("getUser"),
// String with UUID format (inferred type is string, explicit format)
builder.WithPathParam("user_id", "",
builder.WithParamFormat("uuid"),
builder.WithParamDescription("User UUID identifier"),
),
// Override type to integer with int64 format
builder.WithQueryParam("version", 0,
builder.WithParamType("integer"),
builder.WithParamFormat("int64"),
builder.WithParamDescription("API version number"),
),
builder.WithResponse(http.StatusOK, struct {
ID string `json:"id"`
}{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
params := doc.Paths["/users/{user_id}"].Get.Parameters
fmt.Printf("user_id format: %s\n", params[0].Schema.Format)
fmt.Printf("version type: %s\n", params[1].Schema.Type)
fmt.Printf("version format: %s\n", params[1].Schema.Format)
}
Output: user_id format: uuid version type: integer version format: int64
Example (WithParameterConstraints) ¶
Example_withParameterConstraints demonstrates adding parameter constraints.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Pet represents a pet in the store.
type Pet struct {
ID int64 `json:"id" oas:"description=Unique pet identifier"`
Name string `json:"name" oas:"minLength=1,description=Pet name"`
Tag string `json:"tag,omitempty" oas:"description=Optional tag"`
CreatedAt time.Time `json:"created_at" oas:"readOnly=true"`
}
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("Pet Store API").
SetVersion("1.0.0")
// Add operation with constrained parameters
spec.AddOperation(http.MethodGet, "/pets",
builder.WithOperationID("listPets"),
// Numeric constraint: limit must be between 1 and 100, default 20
builder.WithQueryParam("limit", int32(0),
builder.WithParamDescription("Maximum number of pets to return"),
builder.WithParamMinimum(1),
builder.WithParamMaximum(100),
builder.WithParamDefault(20),
),
// Enum constraint: status must be one of the allowed values
builder.WithQueryParam("status", "",
builder.WithParamDescription("Filter by status"),
builder.WithParamEnum("available", "pending", "sold"),
builder.WithParamDefault("available"),
),
// String constraint: name must match pattern and length
builder.WithQueryParam("name", "",
builder.WithParamDescription("Filter by name"),
builder.WithParamMinLength(1),
builder.WithParamMaxLength(50),
builder.WithParamPattern("^[a-zA-Z]+$"),
),
builder.WithResponse(http.StatusOK, []Pet{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
params := doc.Paths["/pets"].Get.Parameters
fmt.Printf("Parameters: %d\n", len(params))
fmt.Printf("limit min: %.0f\n", *params[0].Schema.Minimum)
fmt.Printf("limit max: %.0f\n", *params[0].Schema.Maximum)
fmt.Printf("status enum count: %d\n", len(params[1].Schema.Enum))
fmt.Printf("name pattern: %s\n", params[2].Schema.Pattern)
}
Output: Parameters: 3 limit min: 1 limit max: 100 status enum count: 3 name pattern: ^[a-zA-Z]+$
Example (WithParameters) ¶
Example_withParameters demonstrates adding parameters.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Pet represents a pet in the store.
type Pet struct {
ID int64 `json:"id" oas:"description=Unique pet identifier"`
Name string `json:"name" oas:"minLength=1,description=Pet name"`
Tag string `json:"tag,omitempty" oas:"description=Optional tag"`
CreatedAt time.Time `json:"created_at" oas:"readOnly=true"`
}
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("Pet Store API").
SetVersion("1.0.0").
AddOperation(http.MethodGet, "/pets/{petId}",
builder.WithOperationID("getPet"),
builder.WithPathParam("petId", int64(0),
builder.WithParamDescription("The ID of the pet"),
),
builder.WithQueryParam("include", "",
builder.WithParamDescription("Include related resources"),
),
builder.WithResponse(http.StatusOK, Pet{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
paramCount := len(doc.Paths["/pets/{petId}"].Get.Parameters)
fmt.Printf("Parameters: %d\n", paramCount)
}
Output: Parameters: 2
Example (WithRawSchema) ¶
Example_withRawSchema demonstrates using raw schemas for binary data.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("File Download API").
SetVersion("1.0.0")
// Binary file download response
binarySchema := &parser.Schema{
Type: "string",
Format: "binary",
}
spec.AddOperation(http.MethodGet, "/download/{id}",
builder.WithOperationID("downloadFile"),
builder.WithPathParam("id", int64(0),
builder.WithParamDescription("File ID"),
),
builder.WithResponseRawSchema(http.StatusOK, "application/octet-stream", binarySchema,
builder.WithResponseDescription("Binary file content"),
builder.WithResponseHeader("Content-Disposition", &parser.Header{
Description: "Suggested filename",
Schema: &parser.Schema{Type: "string"},
}),
),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
resp := doc.Paths["/download/{id}"].Get.Responses.Codes["200"]
mediaType := resp.Content["application/octet-stream"]
fmt.Printf("Response content type: application/octet-stream\n")
fmt.Printf("Schema type: %s\n", mediaType.Schema.Type)
fmt.Printf("Schema format: %s\n", mediaType.Schema.Format)
fmt.Printf("Has Content-Disposition header: %v\n", resp.Headers["Content-Disposition"] != nil)
}
Output: Response content type: application/octet-stream Schema type: string Schema format: binary Has Content-Disposition header: true
Example (WithRequestBody) ¶
Example_withRequestBody demonstrates adding request bodies.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
// Pet represents a pet in the store.
type Pet struct {
ID int64 `json:"id" oas:"description=Unique pet identifier"`
Name string `json:"name" oas:"minLength=1,description=Pet name"`
Tag string `json:"tag,omitempty" oas:"description=Optional tag"`
CreatedAt time.Time `json:"created_at" oas:"readOnly=true"`
}
func main() {
type CreatePetRequest struct {
Name string `json:"name" oas:"minLength=1"`
Tag string `json:"tag,omitempty"`
}
spec := builder.New(parser.OASVersion320).
SetTitle("Pet Store API").
SetVersion("1.0.0").
AddOperation(http.MethodPost, "/pets",
builder.WithOperationID("createPet"),
builder.WithRequestBody("application/json", CreatePetRequest{},
builder.WithRequired(true),
builder.WithRequestDescription("Pet to create"),
),
builder.WithResponse(http.StatusCreated, Pet{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
hasRequestBody := doc.Paths["/pets"].Post.RequestBody != nil
fmt.Printf("Has request body: %v\n", hasRequestBody)
}
Output: Has request body: true
Example (WithSecurity) ¶
Example_withSecurity demonstrates security configuration.
package main
import (
"fmt"
"log"
"net/http"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("Secure API").
SetVersion("1.0.0").
AddAPIKeySecurityScheme("api_key", "header", "X-API-Key", "API key authentication").
AddHTTPSecurityScheme("bearer_auth", "bearer", "JWT", "Bearer token authentication").
SetSecurity(
builder.SecurityRequirement("api_key"),
builder.SecurityRequirement("bearer_auth"),
).
AddOperation(http.MethodGet, "/secure",
builder.WithOperationID("secureEndpoint"),
builder.WithResponse(http.StatusOK, struct{}{}),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
schemeCount := len(doc.Components.SecuritySchemes)
securityCount := len(doc.Security)
fmt.Printf("Security schemes: %d\n", schemeCount)
fmt.Printf("Global security requirements: %d\n", securityCount)
}
Output: Security schemes: 2 Global security requirements: 2
Example (WithServer) ¶
Example_withServer demonstrates adding servers.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/builder"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := builder.New(parser.OASVersion320).
SetTitle("My API").
SetVersion("1.0.0").
AddServer("https://api.example.com/v1",
builder.WithServerDescription("Production server"),
).
AddServer("https://staging.example.com/v1",
builder.WithServerDescription("Staging server"),
)
doc, err := spec.BuildOAS3()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Servers: %d\n", len(doc.Servers))
fmt.Printf("First server: %s\n", doc.Servers[0].URL)
}
Output: Servers: 2 First server: https://api.example.com/v1
Index ¶
- func SecurityRequirement(schemeName string, scopes ...string) parser.SecurityRequirement
- type Builder
- func (b *Builder) AddAPIKeySecurityScheme(name string, in string, keyName string, description string) *Builder
- func (b *Builder) AddHTTPSecurityScheme(name string, scheme string, bearerFormat string, description string) *Builder
- func (b *Builder) AddOAuth2SecurityScheme(name string, flows *parser.OAuthFlows, description string) *Builder
- func (b *Builder) AddOpenIDConnectSecurityScheme(name string, openIDConnectURL string, description string) *Builder
- func (b *Builder) AddOperation(method, path string, opts ...OperationOption) *Builder
- func (b *Builder) AddParameter(name string, in string, paramName string, paramType any, opts ...ParamOption) *Builder
- func (b *Builder) AddResponse(name string, description string, responseType any, opts ...ResponseOption) *Builder
- func (b *Builder) AddSecurityScheme(name string, scheme *parser.SecurityScheme) *Builder
- func (b *Builder) AddServer(url string, opts ...ServerOption) *Builder
- func (b *Builder) AddTag(name string, opts ...TagOption) *Builder
- func (b *Builder) AddWebhook(name, method string, opts ...OperationOption) *Builder
- func (b *Builder) BuildOAS2() (*parser.OAS2Document, error)
- func (b *Builder) BuildOAS3() (*parser.OAS3Document, error)
- func (b *Builder) BuildResult() (*parser.ParseResult, error)
- func (b *Builder) DeduplicateSchemas() *Builder
- func (b *Builder) MarshalJSON() ([]byte, error)
- func (b *Builder) MarshalYAML() ([]byte, error)
- func (b *Builder) ParameterRef(name string) string
- func (b *Builder) RegisterType(v any) *parser.Schema
- func (b *Builder) RegisterTypeAs(name string, v any) *parser.Schema
- func (b *Builder) ResponseRef(name string) string
- func (b *Builder) SchemaRef(name string) string
- func (b *Builder) SetContact(contact *parser.Contact) *Builder
- func (b *Builder) SetDescription(desc string) *Builder
- func (b *Builder) SetExternalDocs(externalDocs *parser.ExternalDocs) *Builder
- func (b *Builder) SetInfo(info *parser.Info) *Builder
- func (b *Builder) SetLicense(license *parser.License) *Builder
- func (b *Builder) SetSecurity(requirements ...parser.SecurityRequirement) *Builder
- func (b *Builder) SetTermsOfService(url string) *Builder
- func (b *Builder) SetTitle(title string) *Builder
- func (b *Builder) SetVersion(version string) *Builder
- func (b *Builder) WriteFile(path string) error
- type BuilderOption
- func WithGenericApplyBaseCasing(apply bool) BuilderOption
- func WithGenericIncludePackage(include bool) BuilderOption
- func WithGenericNaming(strategy GenericNamingStrategy) BuilderOption
- func WithGenericNamingConfig(config GenericNamingConfig) BuilderOption
- func WithGenericParamSeparator(sep string) BuilderOption
- func WithGenericSeparator(sep string) BuilderOption
- func WithSchemaNameFunc(fn SchemaNameFunc) BuilderOption
- func WithSchemaNameTemplate(tmpl string) BuilderOption
- func WithSchemaNaming(strategy SchemaNamingStrategy) BuilderOption
- func WithSemanticDeduplication(enabled bool) BuilderOption
- type ConstraintError
- type GenericNamingConfig
- type GenericNamingStrategy
- type OperationOption
- func WithConsumes(mimeTypes ...string) OperationOption
- func WithCookieParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithDefaultResponse(responseType any, opts ...ResponseOption) OperationOption
- func WithDeprecated(deprecated bool) OperationOption
- func WithDescription(desc string) OperationOption
- func WithFileParam(name string, opts ...ParamOption) OperationOption
- func WithFormParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithHeaderParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithNoSecurity() OperationOption
- func WithOperationExtension(key string, value any) OperationOption
- func WithOperationID(id string) OperationOption
- func WithParameter(param *parser.Parameter) OperationOption
- func WithParameterRef(ref string) OperationOption
- func WithPathParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithProduces(mimeTypes ...string) OperationOption
- func WithQueryParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithRequestBody(contentType string, bodyType any, opts ...RequestBodyOption) OperationOption
- func WithRequestBodyContentTypes(contentTypes []string, bodyType any, opts ...RequestBodyOption) OperationOption
- func WithRequestBodyRawSchema(contentType string, schema *parser.Schema, opts ...RequestBodyOption) OperationOption
- func WithResponse(statusCode int, responseType any, opts ...ResponseOption) OperationOption
- func WithResponseContentTypes(statusCode int, contentTypes []string, responseType any, ...) OperationOption
- func WithResponseRawSchema(statusCode int, contentType string, schema *parser.Schema, ...) OperationOption
- func WithResponseRef(statusCode int, ref string) OperationOption
- func WithSecurity(requirements ...parser.SecurityRequirement) OperationOption
- func WithSummary(summary string) OperationOption
- func WithTags(tags ...string) OperationOption
- type ParamOption
- func WithParamAllowEmptyValue(allow bool) ParamOption
- func WithParamCollectionFormat(format string) ParamOption
- func WithParamDefault(value any) ParamOption
- func WithParamDeprecated(deprecated bool) ParamOption
- func WithParamDescription(desc string) ParamOption
- func WithParamEnum(values ...any) ParamOption
- func WithParamExample(example any) ParamOption
- func WithParamExclusiveMaximum(exclusive bool) ParamOption
- func WithParamExclusiveMinimum(exclusive bool) ParamOption
- func WithParamExtension(key string, value any) ParamOption
- func WithParamFormat(format string) ParamOption
- func WithParamMaxItems(max int) ParamOption
- func WithParamMaxLength(max int) ParamOption
- func WithParamMaximum(max float64) ParamOption
- func WithParamMinItems(min int) ParamOption
- func WithParamMinLength(min int) ParamOption
- func WithParamMinimum(min float64) ParamOption
- func WithParamMultipleOf(value float64) ParamOption
- func WithParamPattern(pattern string) ParamOption
- func WithParamRequired(required bool) ParamOption
- func WithParamSchema(schema *parser.Schema) ParamOption
- func WithParamType(typeName string) ParamOption
- func WithParamUniqueItems(unique bool) ParamOption
- type RequestBodyOption
- type ResponseOption
- func WithResponseContentType(contentType string) ResponseOption
- func WithResponseDescription(desc string) ResponseOption
- func WithResponseExample(example any) ResponseOption
- func WithResponseExtension(key string, value any) ResponseOption
- func WithResponseHeader(name string, header *parser.Header) ResponseOption
- type SchemaNameContext
- type SchemaNameFunc
- type SchemaNamingStrategy
- type ServerOption
- type ServerVariableOption
- type TagOption
Examples ¶
- Package
- Package (CompleteAPI)
- Package (FromDocument)
- Package (GenericNamingConfig)
- Package (SchemaGeneration)
- Package (SchemaNamingCustomFunc)
- Package (SchemaNamingPascalCase)
- Package (SchemaNamingTemplate)
- Package (SemanticDeduplication)
- Package (WithComplexRawSchema)
- Package (WithFileUpload)
- Package (WithFormParameters)
- Package (WithParamTypeFormatOverride)
- Package (WithParameterConstraints)
- Package (WithParameters)
- Package (WithRawSchema)
- Package (WithRequestBody)
- Package (WithSecurity)
- Package (WithServer)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SecurityRequirement ¶
func SecurityRequirement(schemeName string, scopes ...string) parser.SecurityRequirement
SecurityRequirement creates a security requirement for use with SetSecurity or WithSecurity.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is the main entry point for constructing OAS documents. It maintains internal state for accumulated components and reflection cache.
Concurrency: Builder instances are not safe for concurrent use. Create separate Builder instances for concurrent operations.
func FromDocument ¶
func FromDocument(doc *parser.OAS3Document) *Builder
FromDocument creates a builder from an existing OAS3Document. This allows modifying an existing document by adding operations.
For OAS 2.0 documents, use FromOAS2Document instead.
func FromOAS2Document ¶
func FromOAS2Document(doc *parser.OAS2Document) *Builder
FromOAS2Document creates a builder from an existing OAS2Document (Swagger 2.0). This allows modifying an existing document by adding operations.
For OAS 3.x documents, use FromDocument instead.
func New ¶
func New(version parser.OASVersion, opts ...BuilderOption) *Builder
New creates a new Builder instance for the specified OAS version. Use BuildOAS2() for OAS 2.0 (Swagger) or BuildOAS3() for OAS 3.x documents.
Options can be provided to customize schema naming:
// Use PascalCase naming (e.g., "ModelsUser" instead of "models.User")
spec := builder.New(parser.OASVersion320,
builder.WithSchemaNaming(builder.SchemaNamingPascalCase),
)
The builder does not perform OAS specification validation. Use the validator package to validate built documents.
Example:
spec := builder.New(parser.OASVersion320).
SetTitle("My API").
SetVersion("1.0.0")
doc, err := spec.BuildOAS3()
func NewWithInfo ¶
func NewWithInfo(version parser.OASVersion, info *parser.Info) *Builder
NewWithInfo creates a Builder with pre-configured Info.
Example:
info := &parser.Info{Title: "My API", Version: "1.0.0"}
spec := builder.NewWithInfo(parser.OASVersion320, info)
func (*Builder) AddAPIKeySecurityScheme ¶
func (b *Builder) AddAPIKeySecurityScheme(name string, in string, keyName string, description string) *Builder
AddAPIKeySecurityScheme adds an API key security scheme.
func (*Builder) AddHTTPSecurityScheme ¶
func (b *Builder) AddHTTPSecurityScheme(name string, scheme string, bearerFormat string, description string) *Builder
AddHTTPSecurityScheme adds an HTTP security scheme (Basic, Bearer, etc.).
func (*Builder) AddOAuth2SecurityScheme ¶
func (b *Builder) AddOAuth2SecurityScheme(name string, flows *parser.OAuthFlows, description string) *Builder
AddOAuth2SecurityScheme adds an OAuth2 security scheme.
func (*Builder) AddOpenIDConnectSecurityScheme ¶
func (b *Builder) AddOpenIDConnectSecurityScheme(name string, openIDConnectURL string, description string) *Builder
AddOpenIDConnectSecurityScheme adds an OpenID Connect security scheme.
func (*Builder) AddOperation ¶
func (b *Builder) AddOperation(method, path string, opts ...OperationOption) *Builder
AddOperation adds an API operation to the specification. Go types passed to options are automatically converted to schemas via reflection.
Note: OpenAPI requires at least one response per operation. If no responses are defined, the resulting spec will fail OAS validation. Use WithResponse() or WithDefaultResponse() to add responses. The builder package does not perform OAS specification validation; use the validator package to validate built documents.
func (*Builder) AddParameter ¶
func (b *Builder) AddParameter(name string, in string, paramName string, paramType any, opts ...ParamOption) *Builder
AddParameter adds a reusable parameter to components.parameters (OAS 3.x) or parameters (OAS 2.0).
Constraint validation is performed and any errors are accumulated in the builder. Use BuildOAS2() or BuildOAS3() to check for accumulated errors.
func (*Builder) AddResponse ¶
func (b *Builder) AddResponse(name string, description string, responseType any, opts ...ResponseOption) *Builder
AddResponse adds a reusable response to components.responses (OAS 3.x) or responses (OAS 2.0). Use WithResponseContentType to specify a content type other than "application/json".
func (*Builder) AddSecurityScheme ¶
func (b *Builder) AddSecurityScheme(name string, scheme *parser.SecurityScheme) *Builder
AddSecurityScheme adds a security scheme to components.securitySchemes.
func (*Builder) AddServer ¶
func (b *Builder) AddServer(url string, opts ...ServerOption) *Builder
AddServer adds a server to the specification.
func (*Builder) AddWebhook ¶
func (b *Builder) AddWebhook(name, method string, opts ...OperationOption) *Builder
AddWebhook adds a webhook to the specification (OAS 3.1+ only). Webhooks are callbacks that are triggered by the API provider. Returns an error during Build if used with OAS versions earlier than 3.1.
Example:
spec.AddWebhook("newUser", http.MethodPost,
builder.WithResponse(http.StatusOK, UserCreatedEvent{}),
)
func (*Builder) BuildOAS2 ¶
func (b *Builder) BuildOAS2() (*parser.OAS2Document, error)
BuildOAS2 creates an OAS 2.0 (Swagger) document. Returns an error if the builder was created with an OAS 3.x version, or if required fields are missing.
The builder does not perform OAS specification validation. Use the validator package to validate built documents.
Example:
spec := builder.New(parser.OASVersion20).
SetTitle("My API").
SetVersion("1.0.0")
doc, err := spec.BuildOAS2()
// doc is *parser.OAS2Document - no type assertion needed
func (*Builder) BuildOAS3 ¶
func (b *Builder) BuildOAS3() (*parser.OAS3Document, error)
BuildOAS3 creates an OAS 3.x document. Returns an error if the builder was created with OAS 2.0 version, or if required fields are missing.
The builder does not perform OAS specification validation. Use the validator package to validate built documents.
Example:
spec := builder.New(parser.OASVersion320).
SetTitle("My API").
SetVersion("1.0.0")
doc, err := spec.BuildOAS3()
// doc is *parser.OAS3Document - no type assertion needed
func (*Builder) BuildResult ¶
func (b *Builder) BuildResult() (*parser.ParseResult, error)
BuildResult creates a ParseResult for compatibility with other packages. This is useful for validating the built document with the validator package.
The builder does not perform OAS specification validation. Use the validator package to validate built documents:
result, err := spec.BuildResult()
if err != nil { return err }
valResult, err := validator.ValidateParsed(result)
func (*Builder) DeduplicateSchemas ¶ added in v1.26.0
DeduplicateSchemas identifies semantically identical schemas and consolidates them to a single canonical schema. This method should be called after all schemas have been added but before Build*() methods.
Schemas are considered semantically identical if they have the same structural properties (type, format, properties, constraints, etc.), ignoring metadata fields like title, description, and examples.
The canonical schema name is selected alphabetically. For example, if "Address" and "Location" schemas are identical, "Address" becomes canonical and all references to "Location" are rewritten to point to "Address".
Returns the Builder for method chaining.
Note: This method is automatically called by Build*() methods when WithSemanticDeduplication(true) is set. Call it manually only if you need to inspect schemaAliases before building.
func (*Builder) MarshalJSON ¶
MarshalJSON returns the document as JSON bytes.
func (*Builder) MarshalYAML ¶
MarshalYAML returns the document as YAML bytes.
func (*Builder) ParameterRef ¶
ParameterRef returns a reference to a named parameter. This method returns the version-appropriate ref path.
func (*Builder) RegisterType ¶
RegisterType registers a Go type and returns a $ref to it. The schema is automatically generated via reflection and added to components.schemas.
func (*Builder) RegisterTypeAs ¶
RegisterTypeAs registers a Go type with a custom schema name.
func (*Builder) ResponseRef ¶
ResponseRef returns a reference to a named response. This method returns the version-appropriate ref path.
func (*Builder) SchemaRef ¶
SchemaRef returns a reference string to a named schema. This method returns the version-appropriate ref path:
- OAS 2.0: "#/definitions/{name}"
- OAS 3.x: "#/components/schemas/{name}"
func (*Builder) SetContact ¶
SetContact sets the contact information in the Info object.
func (*Builder) SetDescription ¶
SetDescription sets the description in the Info object.
func (*Builder) SetExternalDocs ¶
func (b *Builder) SetExternalDocs(externalDocs *parser.ExternalDocs) *Builder
SetExternalDocs sets the external documentation for the document. This is used for providing additional documentation at the document level.
func (*Builder) SetLicense ¶
SetLicense sets the license information in the Info object.
func (*Builder) SetSecurity ¶
func (b *Builder) SetSecurity(requirements ...parser.SecurityRequirement) *Builder
SetSecurity sets the global security requirements.
func (*Builder) SetTermsOfService ¶
SetTermsOfService sets the terms of service URL in the Info object.
func (*Builder) SetVersion ¶
SetVersion sets the version in the Info object. Note: This is the API version, not the OpenAPI specification version.
type BuilderOption ¶ added in v1.25.0
type BuilderOption func(*builderConfig)
BuilderOption configures a Builder instance. Options are applied when creating a new Builder with New().
func WithGenericApplyBaseCasing ¶ added in v1.25.0
func WithGenericApplyBaseCasing(apply bool) BuilderOption
WithGenericApplyBaseCasing applies the base naming strategy to type parameters. When true with SchemaNamingPascalCase, Response[user_profile] becomes ResponseOfUserProfile. Default is false.
func WithGenericIncludePackage ¶ added in v1.25.0
func WithGenericIncludePackage(include bool) BuilderOption
WithGenericIncludePackage includes package names in generic type parameters. When true, Response[models.User] becomes Response_models_User_. Default is false.
func WithGenericNaming ¶ added in v1.25.0
func WithGenericNaming(strategy GenericNamingStrategy) BuilderOption
WithGenericNaming sets the strategy for handling generic type names. The default is GenericNamingUnderscore which produces "Response_User_" format.
Available strategies:
- GenericNamingUnderscore: "Response_User_" (default)
- GenericNamingOf: "ResponseOfUser"
- GenericNamingFor: "ResponseForUser"
- GenericNamingAngleBrackets: "Response<User>" (URI-encoded in $ref)
- GenericNamingFlattened: "ResponseUser"
func WithGenericNamingConfig ¶ added in v1.25.0
func WithGenericNamingConfig(config GenericNamingConfig) BuilderOption
WithGenericNamingConfig provides fine-grained control over generic type naming. This replaces any previous generic naming settings.
Example:
WithGenericNamingConfig(builder.GenericNamingConfig{
Strategy: builder.GenericNamingOf,
ParamSeparator: "And",
ApplyBaseCasing: true,
})
func WithGenericParamSeparator ¶ added in v1.25.0
func WithGenericParamSeparator(sep string) BuilderOption
WithGenericParamSeparator sets the separator between multiple type parameters. Default is "_".
Example:
WithGenericParamSeparator("And")
// Map[string,int] with GenericNamingOf becomes MapOfStringAndOfInt
func WithGenericSeparator ¶ added in v1.25.0
func WithGenericSeparator(sep string) BuilderOption
WithGenericSeparator sets the separator used for generic type parameters. Only applies to GenericNamingUnderscore strategy. Default is "_".
Example:
WithGenericSeparator("__")
// Response[User] becomes Response__User__
func WithSchemaNameFunc ¶ added in v1.25.0
func WithSchemaNameFunc(fn SchemaNameFunc) BuilderOption
WithSchemaNameFunc sets a custom function for schema naming. Provides maximum flexibility for programmatic naming logic. The function receives SchemaNameContext and returns the schema name.
Example:
WithSchemaNameFunc(func(ctx builder.SchemaNameContext) string {
if ctx.IsAnonymous {
return "AnonymousType"
}
return strings.ToUpper(ctx.Package) + "_" + ctx.Type
})
Setting a custom function clears any previously set template.
func WithSchemaNameTemplate ¶ added in v1.25.0
func WithSchemaNameTemplate(tmpl string) BuilderOption
WithSchemaNameTemplate sets a custom Go text/template for schema naming. Template receives SchemaNameContext with type metadata. Template parse errors are returned by Build*() methods.
Available template functions: pascal, camel, snake, kebab, upper, lower, title, sanitize, trimPrefix, trimSuffix, replace, join.
Available context fields:
- .Type: Go type name without package (e.g., "User", "Response[T]")
- .TypeSanitized: Type with generic brackets replaced per GenericNamingStrategy
- .TypeBase: Base type name without generic parameters (e.g., "Response")
- .Package: Package base name (e.g., "models")
- .PackagePath: Full import path (e.g., "github.com/org/models")
- .PackagePathSanitized: PackagePath with slashes replaced
- .IsGeneric: Whether the type has type parameters
- .GenericParams: Type parameter names if IsGeneric is true
- .GenericParamsSanitized: Sanitized type parameter names
- .GenericSuffix: Formatted generic parameters portion
- .IsAnonymous: Whether this is an anonymous struct type
- .IsPointer: Whether the original type was a pointer
- .Kind: The reflect.Kind as a string
Example:
WithSchemaNameTemplate(`{{pascal .Package}}{{pascal .Type}}`)
Template parse errors are returned by BuildOAS3() or BuildOAS2(). If template execution fails at runtime for a specific type (e.g., due to accessing an invalid field), the naming falls back to the default "package.TypeName" format silently. Ensure templates are tested with representative types to avoid unexpected fallback behavior.
Setting a template clears any previously set custom function.
func WithSchemaNaming ¶ added in v1.25.0
func WithSchemaNaming(strategy SchemaNamingStrategy) BuilderOption
WithSchemaNaming sets a built-in schema naming strategy. The default is SchemaNamingDefault which produces "package.TypeName" format.
Available strategies:
- SchemaNamingDefault: "package.TypeName" (e.g., models.User)
- SchemaNamingPascalCase: "PackageTypeName" (e.g., ModelsUser)
- SchemaNamingCamelCase: "packageTypeName" (e.g., modelsUser)
- SchemaNamingSnakeCase: "package_type_name" (e.g., models_user)
- SchemaNamingKebabCase: "package-type-name" (e.g., models-user)
- SchemaNamingTypeOnly: "TypeName" (e.g., User) - may cause conflicts
- SchemaNamingFullPath: "full_path_TypeName" (e.g., github.com_org_models_User)
Setting a naming strategy clears any previously set template or custom function.
func WithSemanticDeduplication ¶ added in v1.26.0
func WithSemanticDeduplication(enabled bool) BuilderOption
WithSemanticDeduplication enables semantic schema deduplication. When enabled, the builder identifies schemas that are structurally identical and consolidates them to a single canonical schema. All references to duplicate schemas are rewritten to point to the canonical schema.
The canonical schema name is selected alphabetically (e.g., if "Address" and "Location" are identical, "Address" becomes canonical).
This option reduces document size when multiple types converge to the same structure. It is disabled by default.
Example:
spec := builder.New(parser.OASVersion320,
builder.WithSemanticDeduplication(true),
)
type ConstraintError ¶ added in v1.13.1
ConstraintError represents an invalid constraint configuration.
func (*ConstraintError) Error ¶ added in v1.13.1
func (e *ConstraintError) Error() string
type GenericNamingConfig ¶ added in v1.25.0
type GenericNamingConfig struct {
// Strategy is the primary generic naming approach.
Strategy GenericNamingStrategy
// Separator is used between base type and parameters.
// Only applies to GenericNamingUnderscore strategy.
// Default: "_"
Separator string
// ParamSeparator is used between multiple type parameters.
// Example with ParamSeparator="_": Map[string,int] -> Map_string_int
// Example with ParamSeparator="And": Map[string,int] -> MapOfStringAndOfInt
// Default: "_"
ParamSeparator string
// IncludePackage includes the type parameter's package in the name.
// Example: Response[models.User] -> Response_models_User (true)
// Example: Response[models.User] -> Response_User (false, default)
IncludePackage bool
// ApplyBaseCasing applies the base naming strategy to type parameters.
// Example with SchemaNamingPascalCase: Response[user_profile] -> ResponseOfUserProfile
ApplyBaseCasing bool
}
GenericNamingConfig provides fine-grained control over generic type naming.
func DefaultGenericNamingConfig ¶ added in v1.25.0
func DefaultGenericNamingConfig() GenericNamingConfig
DefaultGenericNamingConfig returns the default generic naming configuration. This matches the current behavior where brackets are replaced with underscores.
type GenericNamingStrategy ¶ added in v1.25.0
type GenericNamingStrategy int
GenericNamingStrategy defines how generic type parameters are formatted in schema names.
const ( // GenericNamingUnderscore replaces brackets with underscores (default behavior). // Example: Response[User] -> Response_User_ GenericNamingUnderscore GenericNamingStrategy = iota // GenericNamingOf uses "Of" separator between base type and parameters. // Example: Response[User] -> ResponseOfUser GenericNamingOf // GenericNamingFor uses "For" separator. // Example: Response[User] -> ResponseForUser GenericNamingFor // GenericNamingAngleBrackets uses angle brackets (URI-encoded in $ref). // Example: Response[User] -> Response<User> // Note: Produces Response%3CUser%3E in $ref URIs. GenericNamingAngleBrackets // GenericNamingFlattened removes brackets entirely. // Example: Response[User] -> ResponseUser GenericNamingFlattened )
type OperationOption ¶
type OperationOption func(*operationConfig)
OperationOption configures an operation.
func WithConsumes ¶ added in v1.30.0
func WithConsumes(mimeTypes ...string) OperationOption
WithConsumes sets the consumes MIME types for the operation. This is only applicable to OAS 2.0 specifications. For OAS 3.x, use WithRequestBodyContentTypes instead to specify multiple content types.
Example:
builder.AddOperation("POST", "/users",
builder.WithConsumes("application/json", "application/xml"),
builder.WithRequestBody("application/json", User{}),
)
func WithCookieParam ¶
func WithCookieParam(name string, paramType any, opts ...ParamOption) OperationOption
WithCookieParam adds a cookie parameter to the operation.
func WithDefaultResponse ¶
func WithDefaultResponse(responseType any, opts ...ResponseOption) OperationOption
WithDefaultResponse sets the default response for the operation. Use WithResponseContentType to specify a content type other than "application/json".
func WithDeprecated ¶
func WithDeprecated(deprecated bool) OperationOption
WithDeprecated marks the operation as deprecated.
func WithDescription ¶
func WithDescription(desc string) OperationOption
WithDescription sets the operation description.
func WithFileParam ¶ added in v1.15.0
func WithFileParam(name string, opts ...ParamOption) OperationOption
WithFileParam adds a file upload parameter to the operation. This is primarily for OAS 2.0 file uploads using formData parameters with type="file". For OAS 3.x, it automatically creates a multipart/form-data request body with binary format.
Note: Parameter constraints (minLength, maxLength, pattern, etc.) are not applicable to file parameters and will be ignored. Only description, required, and deprecated options are meaningful for file uploads.
Example (OAS 2.0):
WithFileParam("file", WithParamDescription("File to upload"), WithParamRequired(true))
Example (OAS 3.x):
// Automatically generates multipart/form-data request body:
WithFileParam("file", WithParamDescription("File to upload"), WithParamRequired(true))
func WithFormParam ¶ added in v1.14.0
func WithFormParam(name string, paramType any, opts ...ParamOption) OperationOption
WithFormParam adds a form parameter to the operation. The handling differs based on OAS version:
- OAS 2.0: Adds a parameter with in="formData"
- OAS 3.x: Adds to request body with content-type application/x-www-form-urlencoded
Form parameters support all standard parameter options including constraints, description, required flag, default values, and format specifications.
func WithHeaderParam ¶
func WithHeaderParam(name string, paramType any, opts ...ParamOption) OperationOption
WithHeaderParam adds a header parameter to the operation.
func WithNoSecurity ¶
func WithNoSecurity() OperationOption
WithNoSecurity explicitly marks the operation as requiring no security.
func WithOperationExtension ¶ added in v1.30.0
func WithOperationExtension(key string, value any) OperationOption
WithOperationExtension adds a vendor extension (x-* field) to the operation. The key must start with "x-" as per the OpenAPI specification. Extensions are preserved in both OAS 2.0 and OAS 3.x output.
Example:
builder.AddOperation("GET", "/users",
builder.WithOperationExtension("x-rate-limit", 100),
builder.WithOperationExtension("x-internal", true),
)
func WithOperationID ¶
func WithOperationID(id string) OperationOption
WithOperationID sets the operation ID.
func WithParameter ¶
func WithParameter(param *parser.Parameter) OperationOption
WithParameter adds a pre-built parameter to the operation.
func WithParameterRef ¶
func WithParameterRef(ref string) OperationOption
WithParameterRef adds a parameter reference to the operation.
func WithPathParam ¶
func WithPathParam(name string, paramType any, opts ...ParamOption) OperationOption
WithPathParam adds a path parameter to the operation. Note: Path parameters are always required per the OAS spec.
func WithProduces ¶ added in v1.30.0
func WithProduces(mimeTypes ...string) OperationOption
WithProduces sets the produces MIME types for the operation. This is only applicable to OAS 2.0 specifications. For OAS 3.x, use WithResponseContentTypes instead to specify multiple content types.
Example:
builder.AddOperation("GET", "/users/{id}",
builder.WithProduces("application/json", "application/xml"),
builder.WithResponse(200, User{}),
)
func WithQueryParam ¶
func WithQueryParam(name string, paramType any, opts ...ParamOption) OperationOption
WithQueryParam adds a query parameter to the operation.
func WithRequestBody ¶
func WithRequestBody(contentType string, bodyType any, opts ...RequestBodyOption) OperationOption
WithRequestBody sets the request body for the operation. The bodyType is reflected to generate the schema.
func WithRequestBodyContentTypes ¶ added in v1.30.0
func WithRequestBodyContentTypes(contentTypes []string, bodyType any, opts ...RequestBodyOption) OperationOption
WithRequestBodyContentTypes sets the request body for the operation with multiple content types. All content types share the same schema. This is primarily useful for OAS 3.x specifications where the request body content map can contain multiple media types.
For OAS 2.0, only the first content type is used for the body parameter schema, and you should set the consumes array separately using WithConsumes.
Example:
builder.AddOperation("POST", "/users",
builder.WithRequestBodyContentTypes(
[]string{"application/json", "application/xml"},
User{},
builder.WithRequired(true),
),
)
func WithRequestBodyRawSchema ¶ added in v1.15.0
func WithRequestBodyRawSchema(contentType string, schema *parser.Schema, opts ...RequestBodyOption) OperationOption
WithRequestBodyRawSchema sets the request body for the operation with a pre-built schema. This is useful when you need full control over the schema structure or when working with schemas that cannot be easily represented with Go types (e.g., file uploads, oneOf/anyOf).
Example:
schema := &parser.Schema{
Type: "string",
Format: "binary",
}
WithRequestBodyRawSchema("application/octet-stream", schema)
func WithResponse ¶
func WithResponse(statusCode int, responseType any, opts ...ResponseOption) OperationOption
WithResponse adds a response to the operation. The responseType is reflected to generate the schema. Use WithResponseContentType to specify a content type other than "application/json".
func WithResponseContentTypes ¶ added in v1.30.0
func WithResponseContentTypes(statusCode int, contentTypes []string, responseType any, opts ...ResponseOption) OperationOption
WithResponseContentTypes adds a response with multiple content types to the operation. All content types share the same schema. This is primarily useful for OAS 3.x specifications where the response content map can contain multiple media types.
For OAS 2.0, only the first content type is used for the response schema, and you should set the produces array separately using WithProduces.
Example:
builder.AddOperation("GET", "/users/{id}",
builder.WithResponseContentTypes(
200,
[]string{"application/json", "application/xml"},
User{},
builder.WithResponseDescription("User found"),
),
)
func WithResponseRawSchema ¶ added in v1.15.0
func WithResponseRawSchema(statusCode int, contentType string, schema *parser.Schema, opts ...ResponseOption) OperationOption
WithResponseRawSchema adds a response to the operation with a pre-built schema. This is useful when you need full control over the schema structure or when working with schemas that cannot be easily represented with Go types (e.g., file downloads, oneOf/anyOf).
Example:
schema := &parser.Schema{
Type: "string",
Format: "binary",
}
WithResponseRawSchema(200, "application/octet-stream", schema,
WithResponseDescription("File download"))
func WithResponseRef ¶
func WithResponseRef(statusCode int, ref string) OperationOption
WithResponseRef adds a response reference to the operation.
func WithSecurity ¶
func WithSecurity(requirements ...parser.SecurityRequirement) OperationOption
WithSecurity sets the security requirements for the operation.
func WithSummary ¶
func WithSummary(summary string) OperationOption
WithSummary sets the operation summary.
type ParamOption ¶
type ParamOption func(*paramConfig)
ParamOption configures a parameter.
func WithParamAllowEmptyValue ¶ added in v1.30.0
func WithParamAllowEmptyValue(allow bool) ParamOption
WithParamAllowEmptyValue sets whether the parameter allows empty values. This is only applicable to OAS 2.0 specifications for query and formData parameters. Setting this to true allows sending a parameter with an empty value.
Example:
builder.WithQueryParam("filter", "",
builder.WithParamAllowEmptyValue(true),
)
func WithParamCollectionFormat ¶ added in v1.30.0
func WithParamCollectionFormat(format string) ParamOption
WithParamCollectionFormat sets the collection format for array parameters. This is only applicable to OAS 2.0 specifications.
Valid values are:
- "csv": comma separated values (default) - foo,bar
- "ssv": space separated values - foo bar
- "tsv": tab separated values - foo\tbar
- "pipes": pipe separated values - foo|bar
- "multi": corresponds to multiple parameter instances - foo=bar&foo=baz
Example:
builder.WithQueryParam("tags", []string{},
builder.WithParamCollectionFormat("csv"),
)
func WithParamDefault ¶ added in v1.13.1
func WithParamDefault(value any) ParamOption
WithParamDefault sets the default value for the parameter.
func WithParamDeprecated ¶
func WithParamDeprecated(deprecated bool) ParamOption
WithParamDeprecated marks the parameter as deprecated.
func WithParamDescription ¶
func WithParamDescription(desc string) ParamOption
WithParamDescription sets the parameter description.
func WithParamEnum ¶ added in v1.13.1
func WithParamEnum(values ...any) ParamOption
WithParamEnum sets the allowed values for the parameter.
func WithParamExample ¶
func WithParamExample(example any) ParamOption
WithParamExample sets the parameter example.
func WithParamExclusiveMaximum ¶ added in v1.13.1
func WithParamExclusiveMaximum(exclusive bool) ParamOption
WithParamExclusiveMaximum sets whether the maximum is exclusive.
func WithParamExclusiveMinimum ¶ added in v1.13.1
func WithParamExclusiveMinimum(exclusive bool) ParamOption
WithParamExclusiveMinimum sets whether the minimum is exclusive.
func WithParamExtension ¶ added in v1.30.0
func WithParamExtension(key string, value any) ParamOption
WithParamExtension adds a vendor extension (x-* field) to the parameter. The key must start with "x-" as per the OpenAPI specification. Extensions are preserved in both OAS 2.0 and OAS 3.x output.
Example:
builder.WithQueryParam("limit", 0,
builder.WithParamExtension("x-example-values", []int{10, 25, 50}),
)
func WithParamFormat ¶ added in v1.33.0
func WithParamFormat(format string) ParamOption
WithParamFormat sets an explicit OpenAPI format for the parameter. This overrides the format that would be inferred from the Go type.
Common formats include: "int32", "int64", "float", "double", "byte", "binary", "date", "date-time", "password", "email", "uri", "uuid", "hostname", "ipv4", "ipv6".
Example:
builder.WithQueryParam("user_id", "",
builder.WithParamFormat("uuid"),
)
func WithParamMaxItems ¶ added in v1.13.1
func WithParamMaxItems(max int) ParamOption
WithParamMaxItems sets the maximum number of items for array parameters.
func WithParamMaxLength ¶ added in v1.13.1
func WithParamMaxLength(max int) ParamOption
WithParamMaxLength sets the maximum length for string parameters.
func WithParamMaximum ¶ added in v1.13.1
func WithParamMaximum(max float64) ParamOption
WithParamMaximum sets the maximum value for numeric parameters.
func WithParamMinItems ¶ added in v1.13.1
func WithParamMinItems(min int) ParamOption
WithParamMinItems sets the minimum number of items for array parameters.
func WithParamMinLength ¶ added in v1.13.1
func WithParamMinLength(min int) ParamOption
WithParamMinLength sets the minimum length for string parameters.
func WithParamMinimum ¶ added in v1.13.1
func WithParamMinimum(min float64) ParamOption
WithParamMinimum sets the minimum value for numeric parameters.
func WithParamMultipleOf ¶ added in v1.13.1
func WithParamMultipleOf(value float64) ParamOption
WithParamMultipleOf sets the multipleOf constraint for numeric parameters.
func WithParamPattern ¶ added in v1.13.1
func WithParamPattern(pattern string) ParamOption
WithParamPattern sets the pattern (regex) for string parameters.
func WithParamRequired ¶
func WithParamRequired(required bool) ParamOption
WithParamRequired sets whether the parameter is required.
func WithParamSchema ¶ added in v1.33.0
func WithParamSchema(schema *parser.Schema) ParamOption
WithParamSchema sets a complete schema for the parameter. This takes precedence over type/format inference and the WithParamType/WithParamFormat options.
Use this for complex schemas that cannot be easily represented with Go types (e.g., oneOf, arrays with specific item constraints).
Example:
builder.WithQueryParam("ids", nil,
builder.WithParamSchema(&parser.Schema{
Type: "array",
Items: &parser.Schema{Type: "string", Format: "uuid"},
}),
)
func WithParamType ¶ added in v1.33.0
func WithParamType(typeName string) ParamOption
WithParamType sets an explicit OpenAPI type for the parameter. This overrides the type that would be inferred from the Go type.
Valid types per OpenAPI specification: "string", "integer", "number", "boolean", "array", "object".
Example:
builder.WithQueryParam("data", []byte{},
builder.WithParamType("string"),
builder.WithParamFormat("byte"),
)
func WithParamUniqueItems ¶ added in v1.13.1
func WithParamUniqueItems(unique bool) ParamOption
WithParamUniqueItems sets whether array items must be unique.
type RequestBodyOption ¶
type RequestBodyOption func(*requestBodyConfig)
RequestBodyOption configures a request body.
func WithRequestBodyExtension ¶ added in v1.30.0
func WithRequestBodyExtension(key string, value any) RequestBodyOption
WithRequestBodyExtension adds a vendor extension (x-* field) to the request body. The key must start with "x-" as per the OpenAPI specification. Extensions are preserved in OAS 3.x output. For OAS 2.0, request bodies are converted to body parameters, and extensions will be applied to the body parameter.
Example:
builder.AddOperation("POST", "/users",
builder.WithRequestBody("application/json", User{},
builder.WithRequestBodyExtension("x-codegen-request-body-name", "user"),
),
)
func WithRequestDescription ¶
func WithRequestDescription(desc string) RequestBodyOption
WithRequestDescription sets the request body description.
func WithRequestExample ¶
func WithRequestExample(example any) RequestBodyOption
WithRequestExample sets the request body example.
func WithRequired ¶
func WithRequired(required bool) RequestBodyOption
WithRequired sets whether the request body is required.
type ResponseOption ¶
type ResponseOption func(*responseConfig)
ResponseOption configures a response.
func WithResponseContentType ¶
func WithResponseContentType(contentType string) ResponseOption
WithResponseContentType sets the content type for the response. Defaults to "application/json" if not specified.
func WithResponseDescription ¶
func WithResponseDescription(desc string) ResponseOption
WithResponseDescription sets the response description.
func WithResponseExample ¶
func WithResponseExample(example any) ResponseOption
WithResponseExample sets the response example.
func WithResponseExtension ¶ added in v1.30.0
func WithResponseExtension(key string, value any) ResponseOption
WithResponseExtension adds a vendor extension (x-* field) to the response. The key must start with "x-" as per the OpenAPI specification. Extensions are preserved in both OAS 2.0 and OAS 3.x output.
Example:
builder.WithResponse(200, User{},
builder.WithResponseExtension("x-cache-ttl", 3600),
)
func WithResponseHeader ¶
func WithResponseHeader(name string, header *parser.Header) ResponseOption
WithResponseHeader adds a header to the response.
type SchemaNameContext ¶ added in v1.25.0
type SchemaNameContext struct {
// Type is the Go type name without package (e.g., "User", "Response[T]").
Type string
// TypeSanitized is Type with generic brackets replaced per GenericNamingStrategy.
TypeSanitized string
// TypeBase is the base type name without generic parameters (e.g., "Response").
TypeBase string
// Package is the package base name (e.g., "models").
Package string
// PackagePath is the full import path (e.g., "github.com/org/models").
PackagePath string
// PackagePathSanitized is PackagePath with slashes replaced
// (e.g., "github.com_org_models").
PackagePathSanitized string
// IsGeneric indicates if the type has type parameters.
IsGeneric bool
// GenericParams contains the type parameter names if IsGeneric is true.
GenericParams []string
// GenericParamsSanitized contains sanitized type parameter names.
GenericParamsSanitized []string
// GenericSuffix is the formatted generic parameters portion.
// Varies based on GenericNamingStrategy (e.g., "_User_", "OfUser", "<User>").
GenericSuffix string
// IsAnonymous indicates if this is an anonymous struct type.
IsAnonymous bool
// IsPointer indicates if the original type was a pointer.
IsPointer bool
// Kind is the reflect.Kind as a string (e.g., "struct", "slice", "map").
Kind string
}
SchemaNameContext provides type metadata for custom naming templates and functions. All fields are populated before being passed to templates or custom naming functions.
type SchemaNameFunc ¶ added in v1.25.0
type SchemaNameFunc func(ctx SchemaNameContext) string
SchemaNameFunc is the signature for custom schema naming functions. The function receives a SchemaNameContext with complete type metadata and should return the desired schema name.
type SchemaNamingStrategy ¶ added in v1.25.0
type SchemaNamingStrategy int
SchemaNamingStrategy defines built-in schema naming conventions. Use these with WithSchemaNaming to control how schema names are generated from Go types.
const ( // SchemaNamingDefault uses "package.TypeName" format (current behavior). // Example: models.User SchemaNamingDefault SchemaNamingStrategy = iota // SchemaNamingPascalCase uses "PackageTypeName" format. // Example: models.User -> ModelsUser SchemaNamingPascalCase // SchemaNamingCamelCase uses "packageTypeName" format. // Example: models.User -> modelsUser SchemaNamingCamelCase // SchemaNamingSnakeCase uses "package_type_name" format. // Example: models.User -> models_user SchemaNamingSnakeCase // SchemaNamingKebabCase uses "package-type-name" format. // Example: models.User -> models-user SchemaNamingKebabCase // SchemaNamingTypeOnly uses just "TypeName" without package. // Example: models.User -> User // Warning: May cause conflicts with same-named types in different packages. SchemaNamingTypeOnly // SchemaNamingFullPath uses full package path. // Example: models.User -> github.com_org_models_User SchemaNamingFullPath )
type ServerOption ¶
type ServerOption func(*serverConfig)
ServerOption configures a server.
func WithServerDescription ¶
func WithServerDescription(desc string) ServerOption
WithServerDescription sets the server description.
func WithServerVariable ¶
func WithServerVariable(name, defaultValue string, opts ...ServerVariableOption) ServerOption
WithServerVariable adds a variable to the server.
type ServerVariableOption ¶
type ServerVariableOption func(*serverVariableConfig)
ServerVariableOption configures a server variable.
func WithServerVariableDescription ¶
func WithServerVariableDescription(desc string) ServerVariableOption
WithServerVariableDescription sets the description for a server variable.
func WithServerVariableEnum ¶
func WithServerVariableEnum(values ...string) ServerVariableOption
WithServerVariableEnum sets the enum values for a server variable.
type TagOption ¶
type TagOption func(*tagConfig)
TagOption configures a tag.
func WithTagDescription ¶
WithTagDescription sets the tag description.
func WithTagExternalDocs ¶
WithTagExternalDocs sets the external documentation for a tag.