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).
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.
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
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 (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 (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
Index ¶
- func ExtractComponentNameFromRef(ref string) (componentType, name string)
- func ExtractSchemaNameFromRef(ref string, version parser.OASVersion) string
- type Fix
- type FixResult
- type FixType
- type Fixer
- type GenericNamingConfig
- type GenericNamingStrategy
- 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 WithParsed(result parser.ParseResult) Option
- func WithSourceMap(sm *parser.SourceMap) 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
Examples ¶
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.
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
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" )
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
// DryRun when true, collects fixes without modifying the document.
// Useful for previewing what would be changed.
DryRun 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 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 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 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 )