Documentation
¶
Overview ¶
Package parser provides OpenAPI Specification (OAS) parsing functionality.
This package supports parsing and validating OpenAPI specifications across multiple versions, from OAS 2.0 (Swagger) through OAS 3.2.0. It handles YAML and JSON formats, resolves external references, and performs structural validation.
Supported Versions ¶
The parser supports all official OpenAPI Specification releases:
- OAS 2.0 (Swagger): https://spec.openapis.org/oas/v2.0.html
- OAS 3.0.x (3.0.0 through 3.0.4): https://spec.openapis.org/oas/v3.0.0.html
- OAS 3.1.x (3.1.0 through 3.1.2): https://spec.openapis.org/oas/v3.1.0.html
- OAS 3.2.0: https://spec.openapis.org/oas/v3.2.0.html
All schema definitions use JSON Schema Specification Draft 2020-12: https://www.ietf.org/archive/id/draft-bhutton-json-schema-01.html
Release candidate versions (e.g., 3.0.0-rc0) are detected but not officially supported.
Features ¶
- Multi-format parsing (YAML, JSON)
- External reference resolution ($ref)
- Path traversal protection for file references
- Operation ID uniqueness validation
- Status code format validation
- Memory-efficient caching with limits
Security Considerations ¶
The parser implements several security protections:
Path traversal prevention: External file references are restricted to the base directory and its subdirectories using filepath.Rel validation
Cache limits: A maximum of MaxCachedDocuments (default: 1000) external documents can be loaded to prevent memory exhaustion
HTTP(S) references: Remote URL references are not currently supported, limiting attack surface to local filesystem only
Input validation: All numeric status codes, operation IDs, and reference formats are validated before processing
Basic Usage ¶
opts := &parser.Options{
StrictValidation: true,
ResolveRefs: true,
}
result, err := parser.ParseFile("openapi.yaml", opts)
if err != nil {
log.Fatalf("Parse failed: %v", err)
}
if !result.Valid {
for _, issue := range result.Issues {
fmt.Printf("%s: %s\n", issue.Severity, issue.Message)
}
}
Performance Notes ¶
When ResolveRefs is enabled, the parser performs additional marshaling/unmarshaling to resolve external references, which may impact performance on large documents. For read-only validation without reference resolution, set ResolveRefs to false.
The parser maintains internal maps (Extra fields) on all structs to preserve unknown fields during parsing, allowing for extension properties and forward compatibility. This trades some memory for flexibility.
Example ¶
Example demonstrates basic usage of the parser to parse an OpenAPI specification file.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
p := parser.New()
result, err := p.Parse("../testdata/petstore-3.0.yaml")
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Has errors: %v\n", len(result.Errors) > 0)
}
Output: Version: 3.0.3 Has errors: false
Example (Oas2) ¶
Example_oas2 demonstrates parsing an OpenAPI 2.0 (Swagger) specification.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
p := parser.New()
result, err := p.Parse("../testdata/petstore-2.0.yaml")
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
// Type assertion to access OAS 2.0-specific document structure
if doc, ok := result.Document.(*parser.OAS2Document); ok {
fmt.Printf("Swagger: %s\n", doc.Swagger)
}
}
Output: Version: 2.0 Swagger: 2.0
Example (Oas3) ¶
Example_oas3 demonstrates parsing an OpenAPI 3.x specification and accessing version-specific fields.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
p := parser.New()
result, err := p.Parse("../testdata/petstore-3.0.yaml")
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
// Type assertion to access OAS 3.x-specific document structure
if doc, ok := result.Document.(*parser.OAS3Document); ok {
fmt.Printf("OpenAPI: %s\n", doc.OpenAPI)
fmt.Printf("Has paths: %v\n", doc.Paths != nil)
}
}
Output: Version: 3.0.3 OpenAPI: 3.0.3 Has paths: true
Example (ParseBytes) ¶
Example_parseBytes demonstrates parsing an OpenAPI specification from a byte slice.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
specData := `
openapi: 3.0.3
info:
title: Simple API
version: 1.0.0
paths: {}
`
p := parser.New()
result, err := p.ParseBytes([]byte(specData))
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
}
Output: Version: 3.0.3
Example (ParseReader) ¶
Example_parseReader demonstrates parsing an OpenAPI specification from an io.Reader.
package main
import (
"fmt"
"log"
"strings"
"github.com/erraggy/oastools/parser"
)
func main() {
specData := `
openapi: 3.0.3
info:
title: Simple API
version: 1.0.0
paths: {}
`
reader := strings.NewReader(specData)
p := parser.New()
result, err := p.ParseReader(reader)
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
}
Output: Version: 3.0.3
Example (ParseWithRefs) ¶
Example_parseWithRefs demonstrates parsing with reference resolution enabled.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
p := parser.New()
p.ResolveRefs = true
result, err := p.Parse("../testdata/with-external-refs.yaml")
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Has warnings: %v\n", len(result.Warnings) > 0)
}
Output: Version: 3.0.3 Has warnings: false
Example (ParseWithValidation) ¶
Example_parseWithValidation demonstrates parsing with structure validation enabled.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
p := parser.New()
p.ValidateStructure = true
result, err := p.Parse("../testdata/petstore-3.0.yaml")
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Validation errors: %d\n", len(result.Errors))
}
Output: Version: 3.0.3 Validation errors: 0
Index ¶
- Constants
- type Callback
- type Components
- type Contact
- type Discriminator
- type Encoding
- type Example
- type ExternalDocs
- type Header
- type Info
- type Items
- type License
- type Link
- type MediaType
- type OAS2Document
- type OAS3Document
- type OASVersion
- type OAuthFlow
- type OAuthFlows
- type Operation
- type Parameter
- type ParseResult
- type Parser
- type PathItem
- type Paths
- type RefResolver
- func (r *RefResolver) Resolve(doc map[string]interface{}, ref string) (interface{}, error)
- func (r *RefResolver) ResolveAllRefs(doc map[string]interface{}) error
- func (r *RefResolver) ResolveExternal(ref string) (interface{}, error)
- func (r *RefResolver) ResolveLocal(doc map[string]interface{}, ref string) (interface{}, error)
- type Reference
- type RequestBody
- type Response
- type Responses
- type Schema
- type SecurityRequirement
- type SecurityScheme
- type Server
- type ServerVariable
- type Tag
- type XML
Examples ¶
Constants ¶
const ( // ParamInQuery indicates the parameter is passed in the query string ParamInQuery = "query" // ParamInHeader indicates the parameter is passed in a request header ParamInHeader = "header" // ParamInPath indicates the parameter is part of the URL path ParamInPath = "path" // ParamInCookie indicates the parameter is passed as a cookie (OAS 3.0+) ParamInCookie = "cookie" // ParamInFormData indicates the parameter is passed as form data (OAS 2.0 only) ParamInFormData = "formData" // ParamInBody indicates the parameter is in the request body (OAS 2.0 only) ParamInBody = "body" )
Parameter location constants (used in Parameter.In field)
const ( // MaxRefDepth is the maximum depth allowed for nested $ref resolution // This prevents stack overflow from deeply nested (but non-circular) references MaxRefDepth = 100 // MaxCachedDocuments is the maximum number of external documents to cache // This prevents memory exhaustion from documents with many external references MaxCachedDocuments = 100 // MaxFileSize is the maximum size (in bytes) allowed for external reference files // This prevents resource exhaustion from loading arbitrarily large files // Set to 10MB which should be sufficient for most OpenAPI documents MaxFileSize = 10 * 1024 * 1024 // 10MB )
const (
// ResponseDefault represents the default response (for any status code not explicitly defined)
ResponseDefault = "default"
)
Response code constants
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Components ¶
type Components struct {
Schemas map[string]*Schema `yaml:"schemas,omitempty"`
Responses map[string]*Response `yaml:"responses,omitempty"`
Parameters map[string]*Parameter `yaml:"parameters,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty"`
RequestBodies map[string]*RequestBody `yaml:"requestBodies,omitempty"`
Headers map[string]*Header `yaml:"headers,omitempty"`
SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty"`
Links map[string]*Link `yaml:"links,omitempty"`
Callbacks map[string]*Callback `yaml:"callbacks,omitempty"`
// OAS 3.1+ additions
PathItems map[string]*PathItem `yaml:"pathItems,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Components holds reusable objects for different aspects of the OAS (OAS 3.0+)
type Contact ¶
type Contact struct {
Name string `yaml:"name,omitempty"`
URL string `yaml:"url,omitempty"`
Email string `yaml:"email,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Contact information for the exposed API
type Discriminator ¶
type Discriminator struct {
PropertyName string `yaml:"propertyName"`
Mapping map[string]string `yaml:"mapping,omitempty"`
Extra map[string]interface{} `yaml:",inline"`
}
Discriminator represents a discriminator for polymorphism (OAS 3.0+)
type Encoding ¶
type Encoding struct {
ContentType string `yaml:"contentType,omitempty"`
Headers map[string]*Header `yaml:"headers,omitempty"`
Style string `yaml:"style,omitempty"`
Explode *bool `yaml:"explode,omitempty"`
AllowReserved bool `yaml:"allowReserved,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Encoding defines encoding for a specific property (OAS 3.0+)
type Example ¶
type Example struct {
Ref string `yaml:"$ref,omitempty"`
Summary string `yaml:"summary,omitempty"`
Description string `yaml:"description,omitempty"`
Value interface{} `yaml:"value,omitempty"`
ExternalValue string `yaml:"externalValue,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Example represents an example object (OAS 3.0+)
type ExternalDocs ¶
type ExternalDocs struct {
Description string `yaml:"description,omitempty"`
URL string `yaml:"url"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
ExternalDocs allows referencing external documentation
type Header ¶
type Header struct {
Ref string `yaml:"$ref,omitempty"`
Description string `yaml:"description,omitempty"`
Required bool `yaml:"required,omitempty"`
Deprecated bool `yaml:"deprecated,omitempty"` // OAS 3.0+
// OAS 3.0+ fields
Style string `yaml:"style,omitempty"`
Explode *bool `yaml:"explode,omitempty"`
Schema *Schema `yaml:"schema,omitempty"`
Example interface{} `yaml:"example,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty"`
Content map[string]*MediaType `yaml:"content,omitempty"`
// OAS 2.0 fields
Type string `yaml:"type,omitempty"` // OAS 2.0
Format string `yaml:"format,omitempty"` // OAS 2.0
Items *Items `yaml:"items,omitempty"` // OAS 2.0
CollectionFormat string `yaml:"collectionFormat,omitempty"` // OAS 2.0
Default interface{} `yaml:"default,omitempty"` // OAS 2.0
Maximum *float64 `yaml:"maximum,omitempty"` // OAS 2.0
ExclusiveMaximum bool `yaml:"exclusiveMaximum,omitempty"` // OAS 2.0
Minimum *float64 `yaml:"minimum,omitempty"` // OAS 2.0
ExclusiveMinimum bool `yaml:"exclusiveMinimum,omitempty"` // OAS 2.0
MaxLength *int `yaml:"maxLength,omitempty"` // OAS 2.0
MinLength *int `yaml:"minLength,omitempty"` // OAS 2.0
Pattern string `yaml:"pattern,omitempty"` // OAS 2.0
MaxItems *int `yaml:"maxItems,omitempty"` // OAS 2.0
MinItems *int `yaml:"minItems,omitempty"` // OAS 2.0
UniqueItems bool `yaml:"uniqueItems,omitempty"` // OAS 2.0
Enum []interface{} `yaml:"enum,omitempty"` // OAS 2.0
MultipleOf *float64 `yaml:"multipleOf,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Header represents a header object
type Info ¶
type Info struct {
Title string `yaml:"title"`
Description string `yaml:"description,omitempty"`
TermsOfService string `yaml:"termsOfService,omitempty"`
Contact *Contact `yaml:"contact,omitempty"`
License *License `yaml:"license,omitempty"`
Version string `yaml:"version"`
// OAS 3.1+ additions
Summary string `yaml:"summary,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
// and any other fields not explicitly defined in the struct
Extra map[string]interface{} `yaml:",inline"`
}
Info provides metadata about the API Common across all OAS versions (2.0, 3.0, 3.1, 3.2)
type Items ¶
type Items struct {
Type string `yaml:"type"`
Format string `yaml:"format,omitempty"`
Items *Items `yaml:"items,omitempty"`
CollectionFormat string `yaml:"collectionFormat,omitempty"`
Default interface{} `yaml:"default,omitempty"`
Maximum *float64 `yaml:"maximum,omitempty"`
ExclusiveMaximum bool `yaml:"exclusiveMaximum,omitempty"`
Minimum *float64 `yaml:"minimum,omitempty"`
ExclusiveMinimum bool `yaml:"exclusiveMinimum,omitempty"`
MaxLength *int `yaml:"maxLength,omitempty"`
MinLength *int `yaml:"minLength,omitempty"`
Pattern string `yaml:"pattern,omitempty"`
MaxItems *int `yaml:"maxItems,omitempty"`
MinItems *int `yaml:"minItems,omitempty"`
UniqueItems bool `yaml:"uniqueItems,omitempty"`
Enum []interface{} `yaml:"enum,omitempty"`
MultipleOf *float64 `yaml:"multipleOf,omitempty"`
Extra map[string]interface{} `yaml:",inline"`
}
Items represents items object for array parameters (OAS 2.0)
type License ¶
type License struct {
Name string `yaml:"name"`
URL string `yaml:"url,omitempty"`
Identifier string `yaml:"identifier,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
License information for the exposed API
type Link ¶
type Link struct {
Ref string `yaml:"$ref,omitempty"`
OperationRef string `yaml:"operationRef,omitempty"`
OperationID string `yaml:"operationId,omitempty"`
Parameters map[string]interface{} `yaml:"parameters,omitempty"`
RequestBody interface{} `yaml:"requestBody,omitempty"`
Description string `yaml:"description,omitempty"`
Server *Server `yaml:"server,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Link represents a possible design-time link for a response (OAS 3.0+)
type MediaType ¶
type MediaType struct {
Schema *Schema `yaml:"schema,omitempty"`
Example interface{} `yaml:"example,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty"`
Encoding map[string]*Encoding `yaml:"encoding,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
MediaType provides schema and examples for the media type (OAS 3.0+)
type OAS2Document ¶
type OAS2Document struct {
Swagger string `yaml:"swagger"` // Required: "2.0"
Info *Info `yaml:"info"` // Required
Host string `yaml:"host,omitempty"`
BasePath string `yaml:"basePath,omitempty"`
Schemes []string `yaml:"schemes,omitempty"` // e.g., ["http", "https"]
Consumes []string `yaml:"consumes,omitempty"`
Produces []string `yaml:"produces,omitempty"`
Paths Paths `yaml:"paths"` // Required
Definitions map[string]*Schema `yaml:"definitions,omitempty"`
Parameters map[string]*Parameter `yaml:"parameters,omitempty"`
Responses map[string]*Response `yaml:"responses,omitempty"`
SecurityDefinitions map[string]*SecurityScheme `yaml:"securityDefinitions,omitempty"`
Security []SecurityRequirement `yaml:"security,omitempty"`
Tags []*Tag `yaml:"tags,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
OASVersion OASVersion `yaml:"-"`
}
OAS2Document represents an OpenAPI Specification 2.0 (Swagger) document Reference: https://spec.openapis.org/oas/v2.0.html
type OAS3Document ¶
type OAS3Document struct {
OpenAPI string `yaml:"openapi"` // Required: "3.0.x", "3.1.x", or "3.2.x"
Info *Info `yaml:"info"` // Required
Servers []*Server `yaml:"servers,omitempty"`
Paths Paths `yaml:"paths,omitempty"` // Required in 3.0, optional in 3.1+
Webhooks map[string]*PathItem `yaml:"webhooks,omitempty"` // OAS 3.1+
Components *Components `yaml:"components,omitempty"`
Security []SecurityRequirement `yaml:"security,omitempty"`
Tags []*Tag `yaml:"tags,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`
OASVersion OASVersion `yaml:"-"`
// OAS 3.1+ additions
JSONSchemaDialect string `yaml:"jsonSchemaDialect,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
OAS3Document represents an OpenAPI Specification 3.x document Supports OAS 3.0.x, 3.1.x, and 3.2.x References: - OAS 3.0.0: https://spec.openapis.org/oas/v3.0.0.html - OAS 3.1.0: https://spec.openapis.org/oas/v3.1.0.html - OAS 3.2.0: https://spec.openapis.org/oas/v3.2.0.html
type OASVersion ¶
type OASVersion int
OASVersion represents each canonical version of the OpenAPI Specification that may be found at: https://github.com/OAI/OpenAPI-Specification/releases
const ( // Unknown represents an unknown or invalid OAS version Unknown OASVersion = iota // OASVersion20 OpenAPI Specification Version 2.0 (Swagger) OASVersion20 // OASVersion300 OpenAPI Specification Version 3.0.0 OASVersion300 // OASVersion301 OpenAPI Specification Version 3.0.1 OASVersion301 // OASVersion302 OpenAPI Specification Version 3.0.2 OASVersion302 // OASVersion303 OpenAPI Specification Version 3.0.3 OASVersion303 // OASVersion304 OpenAPI Specification Version 3.0.4 OASVersion304 // OASVersion310 OpenAPI Specification Version 3.1.0 OASVersion310 // OASVersion311 OpenAPI Specification Version 3.1.1 OASVersion311 // OASVersion312 OpenAPI Specification Version 3.1.2 OASVersion312 // OASVersion320 OpenAPI Specification Version 3.2.0 OASVersion320 )
func ParseVersion ¶
func ParseVersion(s string) (OASVersion, bool)
ParseVersion will attempt to parse the string s into an OASVersion, and returns false if not valid. This function supports: 1. Exact version matches (e.g., "2.0", "3.0.3") 2. Future patch versions in known major.minor series (e.g., "3.0.5" maps to "3.0.4") 3. Pre-release versions (e.g., "3.0.0-rc0") map to closest match without exceeding base version
For example: - "3.0.5" (not yet released) maps to OASVersion304 (3.0.4) - latest in 3.0.x series - "3.0.0-rc0" maps to OASVersion300 (3.0.0) - the base version - "3.0.5-rc1" maps to OASVersion304 (3.0.4) - closest without exceeding 3.0.5
func (OASVersion) IsValid ¶
func (v OASVersion) IsValid() bool
IsValid returns true if this is a valid version
func (OASVersion) String ¶
func (v OASVersion) String() string
type OAuthFlow ¶
type OAuthFlow struct {
AuthorizationURL string `yaml:"authorizationUrl,omitempty"`
TokenURL string `yaml:"tokenUrl,omitempty"`
RefreshURL string `yaml:"refreshUrl,omitempty"`
Scopes map[string]string `yaml:"scopes"`
Extra map[string]interface{} `yaml:",inline"`
}
OAuthFlow represents configuration for a single OAuth flow (OAS 3.0+)
type OAuthFlows ¶
type OAuthFlows struct {
Implicit *OAuthFlow `yaml:"implicit,omitempty"`
Password *OAuthFlow `yaml:"password,omitempty"`
ClientCredentials *OAuthFlow `yaml:"clientCredentials,omitempty"`
AuthorizationCode *OAuthFlow `yaml:"authorizationCode,omitempty"`
Extra map[string]interface{} `yaml:",inline"`
}
OAuthFlows allows configuration of the supported OAuth Flows (OAS 3.0+)
type Operation ¶
type Operation struct {
Tags []string `yaml:"tags,omitempty"`
Summary string `yaml:"summary,omitempty"`
Description string `yaml:"description,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`
OperationID string `yaml:"operationId,omitempty"`
Parameters []*Parameter `yaml:"parameters,omitempty"`
RequestBody *RequestBody `yaml:"requestBody,omitempty"` // OAS 3.0+
Responses *Responses `yaml:"responses"`
Callbacks map[string]*Callback `yaml:"callbacks,omitempty"` // OAS 3.0+
Deprecated bool `yaml:"deprecated,omitempty"`
Security []SecurityRequirement `yaml:"security,omitempty"`
Servers []*Server `yaml:"servers,omitempty"` // OAS 3.0+
// OAS 2.0 specific
Consumes []string `yaml:"consumes,omitempty"` // OAS 2.0
Produces []string `yaml:"produces,omitempty"` // OAS 2.0
Schemes []string `yaml:"schemes,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Operation describes a single API operation on a path
type Parameter ¶
type Parameter struct {
Ref string `yaml:"$ref,omitempty"`
Name string `yaml:"name"`
In string `yaml:"in"` // "query", "header", "path", "cookie" (OAS 3.0+), "formData", "body" (OAS 2.0)
Description string `yaml:"description,omitempty"`
Required bool `yaml:"required,omitempty"`
Deprecated bool `yaml:"deprecated,omitempty"` // OAS 3.0+
// OAS 3.0+ fields
Style string `yaml:"style,omitempty"`
Explode *bool `yaml:"explode,omitempty"`
AllowReserved bool `yaml:"allowReserved,omitempty"`
Schema *Schema `yaml:"schema,omitempty"`
Example interface{} `yaml:"example,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty"`
Content map[string]*MediaType `yaml:"content,omitempty"`
// OAS 2.0 fields
Type string `yaml:"type,omitempty"` // OAS 2.0
Format string `yaml:"format,omitempty"` // OAS 2.0
AllowEmptyValue bool `yaml:"allowEmptyValue,omitempty"` // OAS 2.0
Items *Items `yaml:"items,omitempty"` // OAS 2.0
CollectionFormat string `yaml:"collectionFormat,omitempty"` // OAS 2.0
Default interface{} `yaml:"default,omitempty"` // OAS 2.0
Maximum *float64 `yaml:"maximum,omitempty"` // OAS 2.0
ExclusiveMaximum bool `yaml:"exclusiveMaximum,omitempty"` // OAS 2.0
Minimum *float64 `yaml:"minimum,omitempty"` // OAS 2.0
ExclusiveMinimum bool `yaml:"exclusiveMinimum,omitempty"` // OAS 2.0
MaxLength *int `yaml:"maxLength,omitempty"` // OAS 2.0
MinLength *int `yaml:"minLength,omitempty"` // OAS 2.0
Pattern string `yaml:"pattern,omitempty"` // OAS 2.0
MaxItems *int `yaml:"maxItems,omitempty"` // OAS 2.0
MinItems *int `yaml:"minItems,omitempty"` // OAS 2.0
UniqueItems bool `yaml:"uniqueItems,omitempty"` // OAS 2.0
Enum []interface{} `yaml:"enum,omitempty"` // OAS 2.0
MultipleOf *float64 `yaml:"multipleOf,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Parameter describes a single operation parameter
type ParseResult ¶
type ParseResult struct {
// Version is the detected OAS version string (e.g., "2.0", "3.0.3", "3.1.0")
Version string
// Data contains the raw parsed data as a map, potentially with resolved $refs
Data map[string]interface{}
// Document contains the version-specific parsed document:
// - *OAS2Document for OpenAPI 2.0
// - *OAS3Document for OpenAPI 3.x
Document interface{}
// Errors contains any parsing or validation errors encountered
Errors []error
// Warnings contains non-fatal issues such as ref resolution failures
Warnings []string
// OASVersion is the enumerated version of the OpenAPI specification
OASVersion OASVersion
}
ParseResult contains the parsed OpenAPI specification and metadata. This structure provides both the raw parsed data and version-specific typed representations of the OpenAPI document.
type Parser ¶
type Parser struct {
// ResolveRefs determines whether to resolve $ref references
ResolveRefs bool
// ValidateStructure determines whether to perform basic structure validation
ValidateStructure bool
}
Parser handles OpenAPI specification parsing
func (*Parser) Parse ¶
func (p *Parser) Parse(specPath string) (*ParseResult, error)
Parse parses an OpenAPI specification file
func (*Parser) ParseBytes ¶
func (p *Parser) ParseBytes(data []byte) (*ParseResult, error)
ParseBytes parses an OpenAPI specification from a byte slice For external references to work, use Parse() with a file path instead
func (*Parser) ParseReader ¶
func (p *Parser) ParseReader(r io.Reader) (*ParseResult, error)
ParseReader parses an OpenAPI specification from an io.Reader
type PathItem ¶
type PathItem struct {
Ref string `yaml:"$ref,omitempty"`
Summary string `yaml:"summary,omitempty"` // OAS 3.0+
Description string `yaml:"description,omitempty"` // OAS 3.0+
Get *Operation `yaml:"get,omitempty"`
Put *Operation `yaml:"put,omitempty"`
Post *Operation `yaml:"post,omitempty"`
Delete *Operation `yaml:"delete,omitempty"`
Options *Operation `yaml:"options,omitempty"`
Head *Operation `yaml:"head,omitempty"`
Patch *Operation `yaml:"patch,omitempty"`
Trace *Operation `yaml:"trace,omitempty"` // OAS 3.0+
Servers []*Server `yaml:"servers,omitempty"` // OAS 3.0+
Parameters []*Parameter `yaml:"parameters,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
PathItem describes the operations available on a single path
type RefResolver ¶
type RefResolver struct {
// contains filtered or unexported fields
}
RefResolver handles $ref resolution in OpenAPI documents
func NewRefResolver ¶
func NewRefResolver(baseDir string) *RefResolver
NewRefResolver creates a new reference resolver
func (*RefResolver) Resolve ¶
func (r *RefResolver) Resolve(doc map[string]interface{}, ref string) (interface{}, error)
Resolve resolves a $ref reference (local or external)
func (*RefResolver) ResolveAllRefs ¶
func (r *RefResolver) ResolveAllRefs(doc map[string]interface{}) error
ResolveAllRefs walks through the entire document and resolves all $ref references
func (*RefResolver) ResolveExternal ¶
func (r *RefResolver) ResolveExternal(ref string) (interface{}, error)
ResolveExternal resolves external file references External refs are in the format: ./file.yaml#/path/to/component or file.yaml#/path/to/component
func (*RefResolver) ResolveLocal ¶
func (r *RefResolver) ResolveLocal(doc map[string]interface{}, ref string) (interface{}, error)
ResolveLocal resolves local references within a document Local refs are in the format: #/path/to/component
type Reference ¶
type Reference struct {
Ref string `yaml:"$ref"`
Summary string `yaml:"summary,omitempty"` // OAS 3.1+
Description string `yaml:"description,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Reference represents a JSON Reference ($ref)
type RequestBody ¶
type RequestBody struct {
Ref string `yaml:"$ref,omitempty"`
Description string `yaml:"description,omitempty"`
Content map[string]*MediaType `yaml:"content"`
Required bool `yaml:"required,omitempty"`
Extra map[string]interface{} `yaml:",inline"`
}
RequestBody describes a single request body (OAS 3.0+)
type Response ¶
type Response struct {
Ref string `yaml:"$ref,omitempty"`
Description string `yaml:"description"`
Headers map[string]*Header `yaml:"headers,omitempty"`
Content map[string]*MediaType `yaml:"content,omitempty"` // OAS 3.0+
Links map[string]*Link `yaml:"links,omitempty"` // OAS 3.0+
// OAS 2.0 specific
Schema *Schema `yaml:"schema,omitempty"` // OAS 2.0
Examples map[string]interface{} `yaml:"examples,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Response describes a single response from an API Operation
type Responses ¶
type Responses struct {
Default *Response `yaml:"default,omitempty"`
Codes map[string]*Response `yaml:",inline"`
}
Responses is a container for the expected responses of an operation
func (*Responses) UnmarshalYAML ¶
UnmarshalYAML implements custom unmarshaling for Responses to validate status codes during parsing. This prevents invalid fields from being captured in the Codes map and provides clearer error messages.
type Schema ¶
type Schema struct {
// JSON Schema Core
Ref string `yaml:"$ref,omitempty"`
Schema string `yaml:"$schema,omitempty"` // JSON Schema Draft version
// Metadata
Title string `yaml:"title,omitempty"`
Description string `yaml:"description,omitempty"`
Default interface{} `yaml:"default,omitempty"`
Examples []interface{} `yaml:"examples,omitempty"` // OAS 3.0+, JSON Schema Draft 2020-12
// Type validation
Type interface{} `yaml:"type,omitempty"` // string or []string (OAS 3.1+)
Enum []interface{} `yaml:"enum,omitempty"`
Const interface{} `yaml:"const,omitempty"` // JSON Schema Draft 2020-12
// Numeric validation
MultipleOf *float64 `yaml:"multipleOf,omitempty"`
Maximum *float64 `yaml:"maximum,omitempty"`
ExclusiveMaximum interface{} `yaml:"exclusiveMaximum,omitempty"` // bool in OAS 2.0/3.0, number in 3.1+
Minimum *float64 `yaml:"minimum,omitempty"`
ExclusiveMinimum interface{} `yaml:"exclusiveMinimum,omitempty"` // bool in OAS 2.0/3.0, number in 3.1+
// String validation
MaxLength *int `yaml:"maxLength,omitempty"`
MinLength *int `yaml:"minLength,omitempty"`
Pattern string `yaml:"pattern,omitempty"`
// Array validation
Items interface{} `yaml:"items,omitempty"` // *Schema or bool (OAS 3.1+)
PrefixItems []*Schema `yaml:"prefixItems,omitempty"` // JSON Schema Draft 2020-12
AdditionalItems interface{} `yaml:"additionalItems,omitempty"` // *Schema or bool
MaxItems *int `yaml:"maxItems,omitempty"`
MinItems *int `yaml:"minItems,omitempty"`
UniqueItems bool `yaml:"uniqueItems,omitempty"`
Contains *Schema `yaml:"contains,omitempty"` // JSON Schema Draft 2020-12
MaxContains *int `yaml:"maxContains,omitempty"` // JSON Schema Draft 2020-12
MinContains *int `yaml:"minContains,omitempty"` // JSON Schema Draft 2020-12
// Object validation
Properties map[string]*Schema `yaml:"properties,omitempty"`
PatternProperties map[string]*Schema `yaml:"patternProperties,omitempty"`
AdditionalProperties interface{} `yaml:"additionalProperties,omitempty"` // *Schema or bool
Required []string `yaml:"required,omitempty"`
PropertyNames *Schema `yaml:"propertyNames,omitempty"` // JSON Schema Draft 2020-12
MaxProperties *int `yaml:"maxProperties,omitempty"`
MinProperties *int `yaml:"minProperties,omitempty"`
DependentRequired map[string][]string `yaml:"dependentRequired,omitempty"` // JSON Schema Draft 2020-12
DependentSchemas map[string]*Schema `yaml:"dependentSchemas,omitempty"` // JSON Schema Draft 2020-12
// Conditional schemas
If *Schema `yaml:"if,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
Then *Schema `yaml:"then,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
Else *Schema `yaml:"else,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
// Schema composition
AllOf []*Schema `yaml:"allOf,omitempty"`
AnyOf []*Schema `yaml:"anyOf,omitempty"`
OneOf []*Schema `yaml:"oneOf,omitempty"`
Not *Schema `yaml:"not,omitempty"`
// OAS specific extensions
Nullable bool `yaml:"nullable,omitempty"` // OAS 3.0 only (replaced by type: [T, "null"] in 3.1+)
Discriminator *Discriminator `yaml:"discriminator,omitempty"` // OAS 3.0+
ReadOnly bool `yaml:"readOnly,omitempty"` // OAS 2.0+
WriteOnly bool `yaml:"writeOnly,omitempty"` // OAS 3.0+
XML *XML `yaml:"xml,omitempty"` // OAS 2.0+
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"` // OAS 2.0+
Example interface{} `yaml:"example,omitempty"` // OAS 2.0, 3.0 (deprecated in 3.1+)
Deprecated bool `yaml:"deprecated,omitempty"` // OAS 3.0+
// Format
Format string `yaml:"format,omitempty"` // e.g., "date-time", "email", "uri", etc.
// OAS 2.0 specific
CollectionFormat string `yaml:"collectionFormat,omitempty"` // OAS 2.0
// JSON Schema Draft 2020-12 additional fields
ID string `yaml:"$id,omitempty"`
Anchor string `yaml:"$anchor,omitempty"`
DynamicRef string `yaml:"$dynamicRef,omitempty"`
DynamicAnchor string `yaml:"$dynamicAnchor,omitempty"`
Vocabulary map[string]bool `yaml:"$vocabulary,omitempty"`
Comment string `yaml:"$comment,omitempty"`
Defs map[string]*Schema `yaml:"$defs,omitempty"`
// Extension fields
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Schema represents a JSON Schema Supports OAS 2.0, OAS 3.0, OAS 3.1+ (JSON Schema Draft 2020-12)
type SecurityRequirement ¶
SecurityRequirement lists the required security schemes to execute an operation Maps security scheme names to scopes (if applicable)
type SecurityScheme ¶
type SecurityScheme struct {
Ref string `yaml:"$ref,omitempty"`
Type string `yaml:"type"` // "apiKey", "http", "oauth2", "openIdConnect" (OAS 3.0+), "basic", "apiKey", "oauth2" (OAS 2.0)
Description string `yaml:"description,omitempty"`
// Type: apiKey (OAS 2.0+, 3.0+)
Name string `yaml:"name,omitempty"` // Header, query, or cookie parameter name
In string `yaml:"in,omitempty"` // "query", "header", "cookie" (OAS 3.0+)
// Type: http (OAS 3.0+)
Scheme string `yaml:"scheme,omitempty"` // e.g., "basic", "bearer"
BearerFormat string `yaml:"bearerFormat,omitempty"` // e.g., "JWT"
// Type: oauth2
Flows *OAuthFlows `yaml:"flows,omitempty"` // OAS 3.0+
// Type: oauth2 (OAS 2.0)
Flow string `yaml:"flow,omitempty"` // "implicit", "password", "application", "accessCode"
AuthorizationURL string `yaml:"authorizationUrl,omitempty"` // OAS 2.0
TokenURL string `yaml:"tokenUrl,omitempty"` // OAS 2.0
Scopes map[string]string `yaml:"scopes,omitempty"` // OAS 2.0
// Type: openIdConnect (OAS 3.0+)
OpenIDConnectURL string `yaml:"openIdConnectUrl,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
SecurityScheme defines a security scheme that can be used by the operations
type Server ¶
type Server struct {
URL string `yaml:"url"`
Description string `yaml:"description,omitempty"`
Variables map[string]ServerVariable `yaml:"variables,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Server represents a Server object (OAS 3.0+)
type ServerVariable ¶
type ServerVariable struct {
Enum []string `yaml:"enum,omitempty"`
Default string `yaml:"default"`
Description string `yaml:"description,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
ServerVariable represents a Server Variable object (OAS 3.0+)
type Tag ¶
type Tag struct {
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]interface{} `yaml:",inline"`
}
Tag adds metadata to a single tag used by operations
type XML ¶
type XML struct {
Name string `yaml:"name,omitempty"`
Namespace string `yaml:"namespace,omitempty"`
Prefix string `yaml:"prefix,omitempty"`
Attribute bool `yaml:"attribute,omitempty"`
Wrapped bool `yaml:"wrapped,omitempty"`
Extra map[string]interface{} `yaml:",inline"`
}
XML represents metadata for XML encoding (OAS 2.0+)