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".
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.
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.
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"),
),
)
See the examples in example_test.go for more patterns.
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 (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 (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", string(""),
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 (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) 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 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 WithHeaderParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithNoSecurity() 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 WithQueryParam(name string, paramType any, opts ...ParamOption) OperationOption
- func WithRequestBody(contentType string, bodyType any, opts ...RequestBodyOption) OperationOption
- func WithResponse(statusCode int, responseType any, opts ...ResponseOption) 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
- type RequestBodyOption
- type ResponseOption
- type ServerOption
- type ServerVariableOption
- type TagOption
Examples ¶
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) *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.
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).
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) 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 OperationOption ¶
type OperationOption func(*operationConfig)
OperationOption configures an operation.
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 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 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 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 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 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 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 WithParamExample ¶
func WithParamExample(example any) ParamOption
WithParamExample sets the parameter example.
func WithParamRequired ¶
func WithParamRequired(required bool) ParamOption
WithParamRequired sets whether the parameter is required.
type RequestBodyOption ¶
type RequestBodyOption func(*requestBodyConfig)
RequestBodyOption configures a request body.
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 WithResponseHeader ¶
func WithResponseHeader(name string, header *parser.Header) ResponseOption
WithResponseHeader adds a header to the response.
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.