Documentation
¶
Overview ¶
Package fixer provides automatic fixes for common OpenAPI Specification validation errors.
The fixer analyzes OAS documents and applies fixes for issues that would cause validation failures. It supports both OAS 2.0 and OAS 3.x documents. The fixer preserves the input file format (JSON or YAML) in the FixResult.SourceFormat field, allowing tools to maintain format consistency when writing output.
Quick Start ¶
Fix a file using functional options:
result, err := fixer.FixWithOptions(
fixer.WithFilePath("openapi.yaml"),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fixes\n", result.FixCount)
Or use a reusable Fixer instance:
f := fixer.New()
f.InferTypes = true // Infer parameter types from naming conventions
result1, _ := f.Fix("api1.yaml")
result2, _ := f.Fix("api2.yaml")
Supported Fixes ¶
The fixer currently supports the following automatic fixes:
Missing path parameters (FixTypeMissingPathParameter): Adds Parameter objects for path template variables that are not declared in the operation's parameters list. For example, if a path is "/users/{userId}" but the operation doesn't declare a "userId" path parameter, the fixer adds one with type "string" (or inferred type if enabled).
Invalid schema names (FixTypeRenamedGenericSchema): Renames schemas with names containing characters that require URL encoding in $ref values. This commonly occurs with code generators that produce generic type names like "Response[User]". The fixer transforms these using configurable naming strategies.
Unused schemas (FixTypePrunedUnusedSchema): Removes schema definitions that are not referenced anywhere in the document. Useful for cleaning up orphaned schemas.
Empty paths (FixTypePrunedEmptyPath): Removes path items that have no HTTP operations defined (e.g., paths with only parameters but no get/post/etc).
CSV enum expansion (FixTypeEnumCSVExpanded): Expands CSV-formatted enum strings to properly-typed arrays. This handles a common pattern from go-restful-openapi where enum values for integer/number types are stored as comma-separated strings (e.g., "1,2,3" instead of [1, 2, 3]). This fix is opt-in and must be explicitly enabled.
Duplicate operationIds (FixTypeDuplicateOperationId): Renames duplicate operationId values within a document. When multiple operations share the same operationId, subsequent occurrences are renamed using a configurable template. The default template "{operationId}{n}" produces names like getUser, getUser2, getUser3. Supports placeholders ({operationId}, {method}, {path}, {tag}, {tags}, {n}) and modifiers (:pascal, :camel, :snake, :kebab, :upper, :lower). This fix is opt-in and must be explicitly enabled.
Stub missing references (FixTypeStubMissingRef): Creates stub definitions for unresolved local $ref pointers to schemas and responses. When a specification references a schema or response that doesn't exist (e.g., "$ref": "#/definitions/MissingType"), this fix creates an empty stub definition to make the document structurally valid. Schemas are stubbed with {} (any value allowed), responses are stubbed with {"description": "<configurable>"}. Only processes local refs (#/...), not external file refs. This fix is opt-in and must be explicitly enabled.
Default Behavior ¶
For performance, only FixTypeMissingPathParameter is enabled by default. The schema renaming and pruning fixes involve expensive operations (walking all references, computing unused schemas) that can significantly slow down processing of large specifications.
To enable additional fixes:
// Enable specific fixes via CLI flags
oastools fix --prune-unused api.yaml
oastools fix --rename-generics --prune-unused api.yaml
// Enable specific fixes programmatically
result, err := fixer.FixWithOptions(
fixer.WithFilePath("api.yaml"),
fixer.WithEnabledFixes(
fixer.FixTypeMissingPathParameter,
fixer.FixTypeRenamedGenericSchema,
fixer.FixTypePrunedUnusedSchema,
),
)
// Enable ALL fixes (backward compatible with pre-v1.28.1)
f := fixer.New()
f.EnabledFixes = []fixer.FixType{} // empty slice enables all
result, _ := f.Fix("api.yaml")
Generic Naming Strategies ¶
When fixing invalid schema names, the following strategies are available:
- GenericNamingUnderscore: Response[User] → Response_User_
- GenericNamingOf: Response[User] → ResponseOfUser
- GenericNamingFor: Response[User] → ResponseForUser
- GenericNamingFlattened: Response[User] → ResponseUser
- GenericNamingDot: Response[User] → Response.User
Configure using WithGenericNaming() or WithGenericNamingConfig() options.
Stub Missing References ¶
When FixTypeStubMissingRef is enabled, the fixer creates empty definitions for unresolved local $ref pointers. This is useful when working with incomplete specifications or when references point to definitions that haven't been created yet.
Enable via CLI:
oastools fix --stub-missing-refs api.yaml oastools fix --stub-missing-refs --stub-response-desc "TODO: implement" api.yaml
Enable programmatically:
result, err := fixer.FixWithOptions(
fixer.WithFilePath("api.yaml"),
fixer.WithEnabledFixes(fixer.FixTypeStubMissingRef),
fixer.WithStubResponseDescription("Stub response - needs implementation"),
)
Supported stub types:
- Schemas: Created as {} (empty object, allows any value)
- Responses: Created with {"description": "<configurable>"} (description is required by spec)
Configure using WithStubConfig() or WithStubResponseDescription() options.
Type Inference ¶
When InferTypes is enabled (--infer flag in CLI), the fixer uses naming conventions to determine parameter types:
- Names ending in "id", "Id", or "ID" -> integer
- Names containing "uuid" or "guid" -> string with format "uuid"
- All other names -> string
Pipeline Usage ¶
The fixer is designed to work in a pipeline with other oastools commands:
# Fix and validate oastools fix api.yaml | oastools validate -q - # Fix and save oastools fix api.yaml -o fixed.yaml
Mutable Input ¶
By default, the fixer deep-copies the parsed document before applying fixes to avoid mutating the caller's data. When the caller owns the input document and does not need it afterward, use WithMutableInput(true) to skip the defensive copy and fix in place. This is especially useful when chaining multiple fixer passes, since each intermediate FixResult.ToParseResult produces a fresh document the caller already owns.
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithMutableInput(true), // skip copy — caller owns input
)
Chaining with Other Packages ¶
Use FixResult.ToParseResult to convert the fix result for use with other packages:
// Fix a specification
fixResult, _ := fixer.FixWithOptions(
fixer.WithFilePath("api.yaml"),
)
// Validate the fixed result
v := validator.New()
validationResult, _ := v.ValidateParsed(*fixResult.ToParseResult())
// Or convert to a different version
c := converter.New()
convResult, _ := c.ConvertParsed(*fixResult.ToParseResult(), "3.1.0")
// Or diff against another document
diffResult, _ := differ.DiffWithOptions(
differ.WithSourceParsed(*fixResult.ToParseResult()),
differ.WithTargetFilePath("production.yaml"),
)
The returned parser.ParseResult uses the source version (the version of the fixed document). Errors and Warnings are empty slices since fixes are informational, not validation errors.
Related Packages ¶
The fixer integrates with other oastools packages:
- github.com/erraggy/oastools/parser - Parse specifications before fixing
- github.com/erraggy/oastools/validator - Validate specifications (use to see errors)
- github.com/erraggy/oastools/converter - Convert between OAS versions
- github.com/erraggy/oastools/joiner - Join multiple specifications
- github.com/erraggy/oastools/differ - Compare specifications
- github.com/erraggy/oastools/generator - Generate code from specifications
- github.com/erraggy/oastools/builder - Programmatically build specifications
Example ¶
Example demonstrates basic usage of the fixer package.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// Parse a spec with missing path parameters
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Fix the specification
f := fixer.New()
result, err := f.FixParsed(*parseResult)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s: %s\n", fix.Type, fix.Description)
}
}
Output: Applied 1 fix(es) missing-path-parameter: Added missing path parameter 'userId' (type: string)
Example (ChainingFixerPasses) ¶
Example_chainingFixerPasses demonstrates chaining multiple fixer passes efficiently using WithMutableInput.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with both missing parameters and unused schemas
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
UnusedSchema:
type: object
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// First pass: add missing path parameters
pass1, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeMissingPathParameter),
)
if err != nil {
log.Fatal(err)
}
// Second pass: prune unused schemas
// pass1 is already a fresh copy we own, so use MutableInput to skip another copy
pass2, err := fixer.FixWithOptions(
fixer.WithParsed(*pass1.ToParseResult()),
fixer.WithMutableInput(true), // Skip copy - we own pass1's document
fixer.WithEnabledFixes(fixer.FixTypePrunedUnusedSchema),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Pass 1: %d fix(es), Pass 2: %d fix(es)\n", pass1.FixCount, pass2.FixCount)
}
Output: Pass 1: 1 fix(es), Pass 2: 1 fix(es)
Example (CsvEnumExpansion) ¶
Example_csvEnumExpansion demonstrates fixing CSV-formatted enum values. Some tools incorrectly represent integer/number enums as comma-separated strings (e.g., "1,2,3" instead of [1, 2, 3]). This fix expands them to proper arrays.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with CSV enum values (common mistake in generated specs)
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/items:
get:
operationId: getItems
parameters:
- name: status
in: query
schema:
type: integer
enum:
- "1,2,3"
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Enable the CSV enum expansion fix (not enabled by default)
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeEnumCSVExpanded),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s: %s\n", fix.Type, fix.Description)
}
}
Output: Applied 1 fix(es) enum-csv-expanded: expanded CSV enum string to 3 individual values
Example (DuplicateOperationId) ¶
Example_duplicateOperationId demonstrates fixing duplicate operationId values. When multiple operations share the same operationId, subsequent occurrences are renamed using a configurable template.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with duplicate operationIds
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users:
get:
operationId: getResource
responses:
'200':
description: Success
/posts:
get:
operationId: getResource
responses:
'200':
description: Success
/comments:
get:
operationId: getResource
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Enable duplicate operationId fixing (not enabled by default)
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeDuplicateOperationId),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s -> %s\n", fix.Before, fix.After)
}
}
Output: Applied 2 fix(es) getResource -> getResource2 getResource -> getResource3
Example (DuplicateOperationIdCustomTemplate) ¶
Example_duplicateOperationIdCustomTemplate demonstrates using a custom template for renaming duplicate operationId values.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with duplicate operationIds
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/posts:
get:
operationId: list
tags:
- posts
responses:
'200':
description: Success
/users:
get:
operationId: list
tags:
- users
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Use a custom template that incorporates the tag name
// Template placeholders: {operationId}, {method}, {path}, {tag}, {tags}, {n}
// Modifiers: :pascal, :camel, :snake, :kebab, :upper, :lower
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeDuplicateOperationId),
fixer.WithOperationIdNamingConfig(fixer.OperationIdNamingConfig{
Template: "{tag:pascal}{operationId:pascal}",
}),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s -> %s\n", fix.Before, fix.After)
}
}
Output: Applied 1 fix(es) list -> UsersList
Example (PruneEmptyPaths) ¶
Example_pruneEmptyPaths demonstrates removing path items with no operations.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with an empty path item (no HTTP methods defined)
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users:
get:
operationId: listUsers
responses:
'200':
description: Success
/empty:
parameters:
- name: version
in: query
schema:
type: string
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Enable only empty path pruning
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypePrunedEmptyPath),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Pruned %d empty path(s)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" Removed: %s\n", fix.Path)
}
}
Output: Pruned 1 empty path(s) Removed: paths./empty
Example (PruneUnusedSchemas) ¶
Example_pruneUnusedSchemas demonstrates removing schemas that are not referenced.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with an orphaned schema (UnusedModel is never referenced)
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users:
get:
operationId: listUsers
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
UnusedModel:
type: object
properties:
name:
type: string
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Enable only the pruning fix
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypePrunedUnusedSchema),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Pruned %d unused schema(s)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" Removed: %s\n", fix.Before)
}
}
Output: Pruned 1 unused schema(s) Removed: UnusedModel
Example (StubMissingRefs) ¶
Example_stubMissingRefs demonstrates creating stub definitions for unresolved local $ref pointers. This is useful when tools generate refs to schemas that don't exist (e.g., from Go any types).
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with references to schemas that don't exist
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/ItemList'
'404':
$ref: '#/components/responses/NotFound'
components:
schemas: {}
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Enable the stub-missing-refs fixer
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeStubMissingRef),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created %d stub(s)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s: %s\n", fix.Path, fix.Description)
}
}
Output: Created 2 stub(s) components.schemas.ItemList: Created stub schema for missing reference #/components/schemas/ItemList components.responses.NotFound: Created stub response for missing reference #/components/responses/NotFound
Example (StubMissingRefsCustomDescription) ¶
Example_stubMissingRefsCustomDescription demonstrates customizing the description for stub responses created by the stub-missing-refs fixer.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with a missing response reference
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/items:
get:
operationId: listItems
responses:
'500':
$ref: '#/components/responses/InternalError'
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Use a custom description for stub responses
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeStubMissingRef),
fixer.WithStubResponseDescription("TODO: Define this response"),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created %d stub(s)\n", result.FixCount)
}
Output: Created 1 stub(s)
Example (Swagger20) ¶
Example_swagger20 demonstrates fixing an OAS 2.0 (Swagger) specification.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := `
swagger: "2.0"
info:
title: Test API
version: 1.0.0
paths:
/pets/{petId}:
get:
operationId: getPet
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
f := fixer.New()
result, err := f.FixParsed(*parseResult)
if err != nil {
log.Fatal(err)
}
fmt.Printf("OAS Version: %s\n", result.SourceVersion)
fmt.Printf("Fixes: %d\n", result.FixCount)
}
Output: OAS Version: 2.0 Fixes: 1
Example (ToParseResult) ¶
Example_toParseResult demonstrates using ToParseResult() to chain fixer output with other packages like validator, converter, or differ.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// Fix a spec with missing path parameters
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
responses:
'200':
description: Success
`
parseResult, err := parser.ParseWithOptions(parser.WithBytes([]byte(spec)))
if err != nil {
log.Fatal(err)
}
fixResult, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
)
if err != nil {
log.Fatal(err)
}
// Convert to ParseResult for use with validator, converter, differ, etc.
result := fixResult.ToParseResult()
// The ParseResult can now be used with other packages:
// - validator.ValidateParsed(*result)
// - converter.ConvertParsed(*result, "3.1.0")
// - differ.DiffParsed(*baseResult, *result)
// SourcePath comes from the original parse (defaults to "ParseBytes.yaml" for bytes)
fmt.Printf("Has source: %v\n", result.SourcePath != "")
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Has document: %v\n", result.Document != nil)
fmt.Printf("Fixes applied: %d\n", fixResult.FixCount)
}
Output: Has source: true Version: 3.0.0 Has document: true Fixes applied: 1
Index ¶
- func ExtractComponentNameFromRef(ref string) (componentType, name string)
- func ExtractSchemaNameFromRef(ref string, version parser.OASVersion) string
- func ParseOperationIdNamingTemplate(template string) error
- type Fix
- type FixResult
- type FixType
- type Fixer
- type GenericNamingConfig
- type GenericNamingStrategy
- type OperationContext
- type OperationIdNamingConfig
- type Option
- func WithDryRun(dryRun bool) Option
- func WithEnabledFixes(fixes ...FixType) Option
- func WithFilePath(path string) Option
- func WithGenericNaming(strategy GenericNamingStrategy) Option
- func WithGenericNamingConfig(config GenericNamingConfig) Option
- func WithInferTypes(infer bool) Option
- func WithMutableInput(mutable bool) Option
- func WithOperationIdNamingConfig(config OperationIdNamingConfig) Option
- func WithParsed(result parser.ParseResult) Option
- func WithSourceMap(sm *parser.SourceMap) Option
- func WithStubConfig(config StubConfig) Option
- func WithStubResponseDescription(desc string) Option
- func WithUserAgent(userAgent string) Option
- type RefCollector
- func (c *RefCollector) CollectOAS2(doc *parser.OAS2Document)
- func (c *RefCollector) CollectOAS3(doc *parser.OAS3Document)
- func (c *RefCollector) GetSchemaRefs() []string
- func (c *RefCollector) GetUnreferencedSchemas(doc any) []string
- func (c *RefCollector) IsCallbackReferenced(name string) bool
- func (c *RefCollector) IsExampleReferenced(name string) bool
- func (c *RefCollector) IsHeaderReferenced(name string, version parser.OASVersion) bool
- func (c *RefCollector) IsLinkReferenced(name string) bool
- func (c *RefCollector) IsParameterReferenced(name string, version parser.OASVersion) bool
- func (c *RefCollector) IsPathItemReferenced(name string) bool
- func (c *RefCollector) IsRequestBodyReferenced(name string) bool
- func (c *RefCollector) IsResponseReferenced(name string, version parser.OASVersion) bool
- func (c *RefCollector) IsSchemaReferenced(name string, version parser.OASVersion) bool
- func (c *RefCollector) IsSecuritySchemeReferenced(name string, version parser.OASVersion) bool
- type RefType
- type StubConfig
Examples ¶
- Package
- Package (ChainingFixerPasses)
- Package (CsvEnumExpansion)
- Package (DuplicateOperationId)
- Package (DuplicateOperationIdCustomTemplate)
- Package (PruneEmptyPaths)
- Package (PruneUnusedSchemas)
- Package (StubMissingRefs)
- Package (StubMissingRefsCustomDescription)
- Package (Swagger20)
- Package (ToParseResult)
- FixResult.HasFixes
- FixWithOptions
- FixWithOptions (GenericNaming)
- GenericNamingStrategy
- ParseGenericNamingStrategy
- WithDryRun
- WithEnabledFixes
- WithGenericNamingConfig
- WithMutableInput
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExtractComponentNameFromRef ¶ added in v1.28.0
ExtractComponentNameFromRef extracts the component name from a reference path. Returns the component type and name, or empty strings if not a valid component reference.
func ExtractSchemaNameFromRef ¶ added in v1.28.0
func ExtractSchemaNameFromRef(ref string, version parser.OASVersion) string
ExtractSchemaNameFromRef extracts the schema name from a reference path. Returns empty string if the reference is not a schema reference.
func ParseOperationIdNamingTemplate ¶ added in v1.43.0
ParseOperationIdNamingTemplate validates that a template contains only valid placeholders and modifiers. Returns an error if the template is empty or contains unknown placeholders or modifiers.
Types ¶
type Fix ¶
type Fix struct {
// Type identifies the category of fix
Type FixType
// Path is the JSON path to the fixed location (e.g., "paths./users/{id}.get.parameters")
Path string
// Description is a human-readable description of the fix
Description string
// Before is the state before the fix (nil if adding new element)
Before any
// After is the value that was added or changed
After any
// Line is the 1-based line number in the source file (0 if unknown)
Line int
// Column is the 1-based column number in the source file (0 if unknown)
Column int
// File is the source file path (empty for main document)
File string
}
Fix represents a single fix applied to the document
func (Fix) HasLocation ¶ added in v1.27.0
HasLocation returns true if this fix has source location information.
type FixResult ¶
type FixResult struct {
// Document contains the fixed document (*parser.OAS2Document or *parser.OAS3Document)
Document any
// SourceVersion is the detected source OAS version string
SourceVersion string
// SourceOASVersion is the enumerated source OAS version
SourceOASVersion parser.OASVersion
// SourceFormat is the format of the source file (JSON or YAML)
SourceFormat parser.SourceFormat
// SourcePath is the path to the source file
SourcePath string
// Fixes contains all fixes applied
Fixes []Fix
// FixCount is the total number of fixes applied
FixCount int
// Success is true if fixing completed without errors
Success bool
// Stats contains statistical information about the document
Stats parser.DocumentStats
}
FixResult contains the results of a fix operation
func FixWithOptions ¶
FixWithOptions fixes an OpenAPI specification using functional options. This provides a flexible, extensible API that combines input source selection and configuration in a single function call.
Example:
result, err := fixer.FixWithOptions(
fixer.WithFilePath("openapi.yaml"),
fixer.WithInferTypes(true),
)
Example ¶
ExampleFixWithOptions demonstrates using functional options.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/projects/{projectId}:
get:
operationId: getProject
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Fix using functional options with type inference
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithInferTypes(true),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s: %s\n", fix.Type, fix.Description)
}
}
Output: Applied 1 fix(es) missing-path-parameter: Added missing path parameter 'projectId' (type: integer)
Example (GenericNaming) ¶
ExampleFixWithOptions_genericNaming demonstrates fixing schemas with invalid names like generic type parameters (e.g., Response[User]).
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with generic-style schema names that need fixing
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users:
get:
operationId: listUsers
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/Response[User]'
components:
schemas:
Response[User]:
type: object
properties:
data:
$ref: '#/components/schemas/User'
User:
type: object
properties:
id:
type: integer
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Fix using the "Of" naming strategy: Response[User] -> ResponseOfUser
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeRenamedGenericSchema),
fixer.WithGenericNaming(fixer.GenericNamingOf),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
if fix.Type == fixer.FixTypeRenamedGenericSchema {
fmt.Printf(" %s -> %s\n", fix.Before, fix.After)
}
}
}
Output: Applied 1 fix(es) Response[User] -> ResponseOfUser
func (*FixResult) HasFixes ¶
HasFixes returns true if any fixes were applied
Example ¶
ExampleFixResult_HasFixes demonstrates checking if fixes were applied.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with no issues needs no fixes
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
parameters:
- name: userId
in: path
required: true
schema:
type: string
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
f := fixer.New()
result, err := f.FixParsed(*parseResult)
if err != nil {
log.Fatal(err)
}
if result.HasFixes() {
fmt.Printf("Applied %d fixes\n", result.FixCount)
} else {
fmt.Println("No fixes needed")
}
}
Output: No fixes needed
func (*FixResult) ToParseResult ¶ added in v1.41.0
func (r *FixResult) ToParseResult() *parser.ParseResult
ToParseResult converts the FixResult to a ParseResult for use with other packages like validator, converter, joiner, and differ. The returned ParseResult has Document populated but Data is nil (consumers use Document, not Data). Errors and Warnings are empty slices since fixes are informational, not validation errors.
type FixType ¶
type FixType string
FixType identifies the type of fix applied
const ( // FixTypeMissingPathParameter indicates a missing path parameter was added FixTypeMissingPathParameter FixType = "missing-path-parameter" // FixTypePrunedEmptyPath indicates an empty path item was removed FixTypePrunedEmptyPath FixType = "pruned-empty-path" // FixTypePrunedUnusedSchema indicates an orphaned schema was removed FixTypePrunedUnusedSchema FixType = "pruned-unused-schema" // FixTypeRenamedGenericSchema indicates a generic type name was simplified FixTypeRenamedGenericSchema FixType = "renamed-generic-schema" // FixTypeEnumCSVExpanded indicates a CSV enum string was expanded to individual values FixTypeEnumCSVExpanded FixType = "enum-csv-expanded" // FixTypeDuplicateOperationId indicates a duplicate operationId was renamed FixTypeDuplicateOperationId FixType = "duplicate-operation-id" // FixTypeStubMissingRef indicates a stub was created for an unresolved reference FixTypeStubMissingRef FixType = "stub-missing-ref" )
type Fixer ¶
type Fixer struct {
// InferTypes enables type inference for path parameters based on naming conventions.
// When true, parameter names ending in "id"/"Id"/"ID" become integer type,
// names containing "uuid"/"guid" become string with format uuid,
// and all others become string type.
InferTypes bool
// EnabledFixes specifies which fix types to apply.
// Defaults to only FixTypeMissingPathParameter for performance.
// Set to include other FixType values to enable additional fixes.
// Set to empty slice ([]FixType{}) or nil to enable all fix types
// (for backward compatibility with pre-v1.28.1 behavior).
EnabledFixes []FixType
// UserAgent is the User-Agent string used when fetching URLs.
// Defaults to "oastools" if not set.
UserAgent string
// SourceMap provides source location lookup for fix issues.
// When set, fixes will include Line, Column, and File information.
SourceMap *parser.SourceMap
// GenericNamingConfig configures how generic type names are transformed
// when fixing invalid schema names (e.g., Response[User] → ResponseOfUser).
GenericNamingConfig GenericNamingConfig
// OperationIdNamingConfig configures how duplicate operationId values are renamed.
// Uses template-based naming with placeholders like {operationId}, {method}, {path}, {n}.
OperationIdNamingConfig OperationIdNamingConfig
// DryRun when true, collects fixes without modifying the document.
// Useful for previewing what would be changed.
DryRun bool
// StubConfig configures how missing reference stubs are created.
StubConfig StubConfig
// MutableInput when true, indicates the caller is transferring ownership
// of the input document and the fixer may mutate it directly instead of
// copying. Default is false (defensive copy for safety).
MutableInput bool
}
Fixer handles automatic fixing of OAS validation issues
func (*Fixer) FixParsed ¶
func (f *Fixer) FixParsed(parseResult parser.ParseResult) (*FixResult, error)
FixParsed fixes an already-parsed OpenAPI specification. The fixer operates on the parsed document structure and does not require a valid specification - it will attempt to fix issues even if validation errors exist (since that's often the reason for using the fixer).
type GenericNamingConfig ¶ added in v1.28.0
type GenericNamingConfig struct {
// Strategy is the primary generic naming approach.
Strategy GenericNamingStrategy
// Separator is used between base type and parameters for underscore strategy.
// Default: "_"
Separator string
// ParamSeparator is used between multiple type parameters.
// Example with ParamSeparator="_": Map[string,int] -> Map_string_int
// Default: "_"
ParamSeparator string
// PreserveCasing when false converts type parameters to PascalCase.
// When true, keeps original casing of type parameters.
// Default: false (convert to PascalCase)
PreserveCasing bool
}
GenericNamingConfig provides fine-grained control over generic type naming.
func DefaultGenericNamingConfig ¶ added in v1.28.0
func DefaultGenericNamingConfig() GenericNamingConfig
DefaultGenericNamingConfig returns the default generic naming configuration. This uses underscore strategy with "_" separators and converts params to PascalCase.
type GenericNamingStrategy ¶ added in v1.28.0
type GenericNamingStrategy int
GenericNamingStrategy defines how generic type parameters are formatted in schema names when transforming invalid names to valid ones.
Example ¶
ExampleGenericNamingStrategy demonstrates the available naming strategies.
package main
import (
"fmt"
"github.com/erraggy/oastools/fixer"
)
func main() {
// Show all available strategies
strategies := []fixer.GenericNamingStrategy{
fixer.GenericNamingUnderscore,
fixer.GenericNamingOf,
fixer.GenericNamingFor,
fixer.GenericNamingFlattened,
fixer.GenericNamingDot,
}
fmt.Println("Available strategies:")
for _, s := range strategies {
fmt.Printf(" %s\n", s)
}
}
Output: Available strategies: underscore of for flattened dot
const ( // GenericNamingUnderscore replaces brackets with underscores. // 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 // GenericNamingFlattened removes brackets entirely. // Example: Response[User] -> ResponseUser GenericNamingFlattened // GenericNamingDot uses dots as separator. // Example: Response[User] -> Response.User GenericNamingDot )
func ParseGenericNamingStrategy ¶ added in v1.28.0
func ParseGenericNamingStrategy(s string) (GenericNamingStrategy, error)
ParseGenericNamingStrategy parses a string into a GenericNamingStrategy. Supported values: "underscore", "of", "for", "flattened", "dot" (case-insensitive).
Example ¶
ExampleParseGenericNamingStrategy demonstrates parsing strategy names from strings.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
)
func main() {
strategies := []string{"of", "for", "underscore", "flattened", "dot"}
for _, s := range strategies {
strategy, err := fixer.ParseGenericNamingStrategy(s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s -> %s\n", s, strategy)
}
}
Output: of -> of for -> for underscore -> underscore flattened -> flattened dot -> dot
func (GenericNamingStrategy) String ¶ added in v1.28.0
func (s GenericNamingStrategy) String() string
String returns the string representation of a GenericNamingStrategy.
type OperationContext ¶ added in v1.43.0
type OperationContext struct {
// OperationId is the original operationId value
OperationId string
// Method is the HTTP method in lowercase (get, post, put, etc.)
Method string
// Path is the API path (e.g., /users/{id}/posts)
Path string
// Tags is the list of tags from the operation
Tags []string
}
OperationContext provides metadata about an operation for template expansion.
type OperationIdNamingConfig ¶ added in v1.43.0
type OperationIdNamingConfig struct {
// Template is the naming template for duplicate operationIds.
// Supported placeholders:
// {operationId} - Original operationId value
// {method} - HTTP method (lowercase: get, post, etc.)
// {path} - Sanitized path (e.g., /users/{id} -> users_id)
// {tag} - First tag (empty string if no tags)
// {tags} - All tags joined with TagSeparator
// {n} - Numeric suffix (2, 3, 4, ...) for collision resolution
//
// Supported modifiers (appended with colon):
// :pascal - PascalCase (e.g., {operationId:pascal} -> "GetUser")
// :camel - camelCase (e.g., {method:camel} -> "get")
// :snake - snake_case (e.g., {path:snake} -> "users_id")
// :kebab - kebab-case (e.g., {tag:kebab} -> "user-profile")
// :upper - UPPERCASE (e.g., {method:upper} -> "GET")
// :lower - lowercase (e.g., {operationId:lower} -> "getuser")
//
// Default: "{operationId}{n}" produces getUser, getUser2, getUser3, ...
Template string
// PathSeparator is used when expanding {path} placeholder.
// Path segments and parameter names are joined with this separator.
// Default: "_"
PathSeparator string
// TagSeparator is used when expanding {tags} placeholder.
// Multiple tags are joined with this separator.
// Default: "_"
TagSeparator string
}
OperationIdNamingConfig configures how duplicate operationId values are renamed. The Template field supports placeholders that are expanded with operation context.
func DefaultOperationIdNamingConfig ¶ added in v1.43.0
func DefaultOperationIdNamingConfig() OperationIdNamingConfig
DefaultOperationIdNamingConfig returns the default configuration. Uses "{operationId}{n}" template which produces: getUser, getUser2, getUser3, ...
type Option ¶
type Option func(*fixConfig) error
Option is a function that configures a fix operation
func WithDryRun ¶ added in v1.28.0
WithDryRun enables dry-run mode, which collects fixes without actually modifying the document. Useful for previewing changes.
Example ¶
ExampleWithDryRun demonstrates previewing fixes without applying them.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Preview what fixes would be applied
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithDryRun(true),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Would apply %d fix(es):\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" %s: %s\n", fix.Type, fix.Description)
}
}
Output: Would apply 1 fix(es): missing-path-parameter: Added missing path parameter 'userId' (type: string)
func WithEnabledFixes ¶
WithEnabledFixes specifies which fix types to apply
Example ¶
ExampleWithEnabledFixes demonstrates selectively enabling specific fix types.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with both missing parameters and invalid schema names
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/Response[User]'
components:
schemas:
Response[User]:
type: object
User:
type: object
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Only fix missing path parameters, ignore invalid schema names
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeMissingPathParameter),
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
for _, fix := range result.Fixes {
fmt.Printf(" Type: %s\n", fix.Type)
}
}
Output: Applied 1 fix(es) Type: missing-path-parameter
func WithFilePath ¶
WithFilePath specifies the file path (local file or URL) to fix
func WithGenericNaming ¶ added in v1.28.0
func WithGenericNaming(strategy GenericNamingStrategy) Option
WithGenericNaming sets the naming strategy for fixing invalid schema names. This applies to schemas with names like "Response[User]" that contain characters requiring URL encoding in $ref values.
func WithGenericNamingConfig ¶ added in v1.28.0
func WithGenericNamingConfig(config GenericNamingConfig) Option
WithGenericNamingConfig sets the full generic naming configuration.
Example ¶
ExampleWithGenericNamingConfig demonstrates fine-grained control over generic type name transformations.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/Map[string,Item]'
components:
schemas:
Map[string,Item]:
type: object
Item:
type: object
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// Configure custom naming with underscore strategy
config := fixer.GenericNamingConfig{
Strategy: fixer.GenericNamingUnderscore,
Separator: "_",
ParamSeparator: "_",
PreserveCasing: false, // Convert to PascalCase
}
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithEnabledFixes(fixer.FixTypeRenamedGenericSchema),
fixer.WithGenericNamingConfig(config),
)
if err != nil {
log.Fatal(err)
}
for _, fix := range result.Fixes {
if fix.Type == fixer.FixTypeRenamedGenericSchema {
fmt.Printf("Renamed: %s -> %s\n", fix.Before, fix.After)
}
}
}
Output: Renamed: Map[string,Item] -> Map_String_Item_
func WithInferTypes ¶
WithInferTypes enables type inference for path parameters
func WithMutableInput ¶ added in v1.48.0
WithMutableInput indicates the caller is transferring ownership of the input document and the fixer may mutate it directly instead of copying. Default is false (defensive copy for safety).
Use this when:
- You've already copied the document for your own use
- You're chaining multiple fixer passes
- Memory efficiency is critical
WARNING: When true, the input document will be mutated. Do not use the original document after calling FixWithOptions.
Example ¶
ExampleWithMutableInput demonstrates skipping the defensive copy when the caller owns the input document. This is useful for chaining multiple fixer passes or when memory efficiency is critical.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/fixer"
"github.com/erraggy/oastools/parser"
)
func main() {
// A spec with missing path parameters
spec := `
openapi: 3.0.0
info:
title: Test API
version: 1.0.0
paths:
/users/{userId}:
get:
operationId: getUser
responses:
'200':
description: Success
`
p := parser.New()
parseResult, err := p.ParseBytes([]byte(spec))
if err != nil {
log.Fatal(err)
}
// When you own the document and want to avoid the defensive copy:
// - You've already copied the document for your own mutations
// - You're chaining multiple fixer passes
// - Memory efficiency is critical for large specs
//
// WARNING: The original document will be mutated!
result, err := fixer.FixWithOptions(
fixer.WithParsed(*parseResult),
fixer.WithMutableInput(true), // Skip internal copy
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Applied %d fix(es)\n", result.FixCount)
}
Output: Applied 1 fix(es)
func WithOperationIdNamingConfig ¶ added in v1.43.0
func WithOperationIdNamingConfig(config OperationIdNamingConfig) Option
WithOperationIdNamingConfig sets the configuration for renaming duplicate operationIds. The config includes a template with placeholders: {operationId}, {method}, {path}, {tag}, {tags}, {n}.
func WithParsed ¶
func WithParsed(result parser.ParseResult) Option
WithParsed specifies an already-parsed specification to fix
func WithSourceMap ¶ added in v1.27.0
WithSourceMap provides a SourceMap for populating line/column information in fix records. When set, fixes will include source location details that enable IDE-friendly error reporting.
func WithStubConfig ¶ added in v1.46.0
func WithStubConfig(config StubConfig) Option
WithStubConfig sets the configuration for missing reference stubs.
func WithStubResponseDescription ¶ added in v1.46.0
WithStubResponseDescription sets the description for stub responses.
func WithUserAgent ¶
WithUserAgent sets the User-Agent string for HTTP requests
type RefCollector ¶ added in v1.28.0
type RefCollector struct {
// Refs maps reference paths to their locations in the document.
// Key: normalized reference path (e.g., "#/components/schemas/Pet")
// Value: list of JSON paths where the reference appears
Refs map[string][]string
// RefsByType categorizes references by their target type.
// Key: RefType (schema, parameter, etc.)
// Value: set of reference paths of that type
RefsByType map[RefType]map[string]bool
// contains filtered or unexported fields
}
RefCollector traverses OpenAPI documents to collect all $ref values. It tracks where references appear in the document and categorizes them by type.
func NewRefCollector ¶ added in v1.28.0
func NewRefCollector() *RefCollector
NewRefCollector creates a new RefCollector instance.
func (*RefCollector) CollectOAS2 ¶ added in v1.28.0
func (c *RefCollector) CollectOAS2(doc *parser.OAS2Document)
CollectOAS2 collects all references from an OAS 2.0 document.
func (*RefCollector) CollectOAS3 ¶ added in v1.28.0
func (c *RefCollector) CollectOAS3(doc *parser.OAS3Document)
CollectOAS3 collects all references from an OAS 3.x document.
func (*RefCollector) GetSchemaRefs ¶ added in v1.28.0
func (c *RefCollector) GetSchemaRefs() []string
GetSchemaRefs returns all schema reference paths that were collected.
func (*RefCollector) GetUnreferencedSchemas ¶ added in v1.28.0
func (c *RefCollector) GetUnreferencedSchemas(doc any) []string
GetUnreferencedSchemas returns the names of schemas that are defined but not referenced. For OAS 2.0, it checks definitions. For OAS 3.x, it checks components/schemas.
func (*RefCollector) IsCallbackReferenced ¶ added in v1.28.0
func (c *RefCollector) IsCallbackReferenced(name string) bool
IsCallbackReferenced returns true if a callback with the given name is referenced.
func (*RefCollector) IsExampleReferenced ¶ added in v1.28.0
func (c *RefCollector) IsExampleReferenced(name string) bool
IsExampleReferenced returns true if an example with the given name is referenced.
func (*RefCollector) IsHeaderReferenced ¶ added in v1.28.0
func (c *RefCollector) IsHeaderReferenced(name string, version parser.OASVersion) bool
IsHeaderReferenced returns true if a header with the given name is referenced.
func (*RefCollector) IsLinkReferenced ¶ added in v1.28.0
func (c *RefCollector) IsLinkReferenced(name string) bool
IsLinkReferenced returns true if a link with the given name is referenced.
func (*RefCollector) IsParameterReferenced ¶ added in v1.28.0
func (c *RefCollector) IsParameterReferenced(name string, version parser.OASVersion) bool
IsParameterReferenced returns true if a parameter with the given name is referenced.
func (*RefCollector) IsPathItemReferenced ¶ added in v1.28.0
func (c *RefCollector) IsPathItemReferenced(name string) bool
IsPathItemReferenced returns true if a path item with the given name is referenced.
func (*RefCollector) IsRequestBodyReferenced ¶ added in v1.28.0
func (c *RefCollector) IsRequestBodyReferenced(name string) bool
IsRequestBodyReferenced returns true if a request body with the given name is referenced. This is only applicable for OAS 3.x documents.
func (*RefCollector) IsResponseReferenced ¶ added in v1.28.0
func (c *RefCollector) IsResponseReferenced(name string, version parser.OASVersion) bool
IsResponseReferenced returns true if a response with the given name is referenced.
func (*RefCollector) IsSchemaReferenced ¶ added in v1.28.0
func (c *RefCollector) IsSchemaReferenced(name string, version parser.OASVersion) bool
IsSchemaReferenced returns true if a schema with the given name is referenced.
func (*RefCollector) IsSecuritySchemeReferenced ¶ added in v1.28.0
func (c *RefCollector) IsSecuritySchemeReferenced(name string, version parser.OASVersion) bool
IsSecuritySchemeReferenced returns true if a security scheme with the given name is referenced. Note: Security schemes are typically referenced by name in the security array, not via $ref. This method checks for explicit $ref usage which is rare but valid.
type RefType ¶ added in v1.28.0
type RefType int
RefType categorizes reference targets by their component type.
const ( // RefTypeSchema represents references to schema definitions RefTypeSchema RefType = iota // RefTypeParameter represents references to parameter definitions RefTypeParameter // RefTypeResponse represents references to response definitions RefTypeResponse // RefTypeRequestBody represents references to request body definitions (OAS 3.x only) RefTypeRequestBody // RefTypeHeader represents references to header definitions RefTypeHeader // RefTypeSecurityScheme represents references to security scheme definitions RefTypeSecurityScheme // RefTypeLink represents references to link definitions (OAS 3.x only) RefTypeLink // RefTypeCallback represents references to callback definitions (OAS 3.x only) RefTypeCallback // RefTypeExample represents references to example definitions (OAS 3.x only) RefTypeExample // RefTypePathItem represents references to path item definitions (OAS 3.1+ only) RefTypePathItem )
type StubConfig ¶ added in v1.46.0
type StubConfig struct {
// ResponseDescription is the description text for stub responses.
// If empty, defaults to DefaultStubConfig().ResponseDescription.
ResponseDescription string
}
StubConfig configures how missing reference stubs are created.
func DefaultStubConfig ¶ added in v1.46.0
func DefaultStubConfig() StubConfig
DefaultStubConfig returns the default configuration for stub creation.