builder

package
v1.22.2 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 15 Imported by: 0

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.

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

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"),
	),
)

See the examples in example_test.go for more patterns.

The builder integrates with other oastools packages:

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

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

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

func (b *Builder) AddTag(name string, opts ...TagOption) *Builder

AddTag adds a tag 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

func (b *Builder) MarshalJSON() ([]byte, error)

MarshalJSON returns the document as JSON bytes.

func (*Builder) MarshalYAML

func (b *Builder) MarshalYAML() ([]byte, error)

MarshalYAML returns the document as YAML bytes.

func (*Builder) ParameterRef

func (b *Builder) ParameterRef(name string) string

ParameterRef returns a reference to a named parameter. This method returns the version-appropriate ref path.

func (*Builder) RegisterType

func (b *Builder) RegisterType(v any) *parser.Schema

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

func (b *Builder) RegisterTypeAs(name string, v any) *parser.Schema

RegisterTypeAs registers a Go type with a custom schema name.

func (*Builder) ResponseRef

func (b *Builder) ResponseRef(name string) string

ResponseRef returns a reference to a named response. This method returns the version-appropriate ref path.

func (*Builder) SchemaRef

func (b *Builder) SchemaRef(name string) string

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

func (b *Builder) SetContact(contact *parser.Contact) *Builder

SetContact sets the contact information in the Info object.

func (*Builder) SetDescription

func (b *Builder) SetDescription(desc string) *Builder

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

func (b *Builder) SetInfo(info *parser.Info) *Builder

SetInfo sets the Info object for the document.

func (*Builder) SetLicense

func (b *Builder) SetLicense(license *parser.License) *Builder

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

func (b *Builder) SetTermsOfService(url string) *Builder

SetTermsOfService sets the terms of service URL in the Info object.

func (*Builder) SetTitle

func (b *Builder) SetTitle(title string) *Builder

SetTitle sets the title in the Info object.

func (*Builder) SetVersion

func (b *Builder) SetVersion(version string) *Builder

SetVersion sets the version in the Info object. Note: This is the API version, not the OpenAPI specification version.

func (*Builder) WriteFile

func (b *Builder) WriteFile(path string) error

WriteFile writes the document to a file. The format is inferred from the file extension (.json for JSON, .yaml/.yml for YAML).

type ConstraintError added in v1.13.1

type ConstraintError struct {
	Field   string
	Message string
}

ConstraintError represents an invalid constraint configuration.

func (*ConstraintError) Error added in v1.13.1

func (e *ConstraintError) Error() string

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

func WithTags

func WithTags(tags ...string) OperationOption

WithTags sets the operation tags.

type ParamOption

type ParamOption func(*paramConfig)

ParamOption configures a parameter.

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

func WithTagDescription(desc string) TagOption

WithTagDescription sets the tag description.

func WithTagExternalDocs

func WithTagExternalDocs(url, description string) TagOption

WithTagExternalDocs sets the external documentation for a tag.

Jump to

Keyboard shortcuts

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