Documentation
¶
Overview ¶
Package parser provides parsing for OpenAPI Specification documents.
The parser supports OAS 2.0 through OAS 3.2.0 in YAML and JSON formats. It can resolve external references ($ref), validate structure, and preserve unknown fields for forward compatibility and extension properties. The parser can load specifications from local files or remote URLs (http:// or https://).
Quick Start ¶
Parse a file using functional options:
result, err := parser.ParseWithOptions(
parser.WithFilePath("openapi.yaml"),
parser.WithValidateStructure(true),
)
if err != nil {
log.Fatal(err)
}
if len(result.Errors) > 0 {
fmt.Printf("Parse errors: %d\n", len(result.Errors))
}
Parse from a URL:
result, err := parser.ParseWithOptions(
parser.WithFilePath("https://example.com/api/openapi.yaml"),
parser.WithValidateStructure(true),
)
if err != nil {
log.Fatal(err)
}
Or create a reusable Parser instance:
p := parser.New()
p.ResolveRefs = false
result1, _ := p.Parse("api1.yaml")
result2, _ := p.Parse("https://example.com/api2.yaml")
Features and Security ¶
The parser validates operation IDs, status codes, and HTTP status codes. For external references, it prevents path traversal attacks by restricting file access to the base directory and subdirectories. Reference resolution caches up to 1000 documents to prevent memory exhaustion.
HTTP/HTTPS $ref resolution is available via WithResolveHTTPRefs (opt-in for security). Use WithInsecureSkipVerify for self-signed certificates. HTTP responses are cached, size-limited, and protected against circular references. See the examples in example_test.go for more details.
ParseResult Fields ¶
ParseResult includes the detected Version, OASVersion, SourceFormat (JSON or YAML), and any parsing Errors or Warnings. The Document field contains the parsed OAS2Document or OAS3Document. The SourceFormat field can be used by conversion and joining tools to preserve the original file format. See the exported ParseResult and document type fields for complete details.
Related Packages ¶
After parsing, use these packages for additional operations:
- github.com/erraggy/oastools/validator - Validate specifications against OAS rules
- github.com/erraggy/oastools/fixer - Fix common validation errors automatically
- github.com/erraggy/oastools/converter - Convert between OAS versions (2.0 ↔ 3.x)
- github.com/erraggy/oastools/joiner - Join multiple specifications into one
- github.com/erraggy/oastools/differ - Compare specifications and detect breaking changes
- github.com/erraggy/oastools/generator - Generate Go code from specifications
- github.com/erraggy/oastools/builder - Programmatically build specifications
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 (FunctionalOptions) ¶
Example_functionalOptions demonstrates parsing using functional options.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
result, err := parser.ParseWithOptions(
parser.WithFilePath("../testdata/petstore-3.0.yaml"),
parser.WithValidateStructure(true),
parser.WithResolveRefs(false),
)
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Format: %s\n", result.SourceFormat)
}
Output: Version: 3.0.3 Format: yaml
Example (ParseFromURL) ¶
Example_parseFromURL demonstrates parsing a specification directly from a URL.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
result, err := parser.ParseWithOptions(
parser.WithFilePath("https://petstore.swagger.io/v2/swagger.json"),
parser.WithValidateStructure(true),
)
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Format: %s\n", result.SourceFormat)
}
Example (ParseWithHTTPRefs) ¶
Example_parseWithHTTPRefs demonstrates parsing with HTTP/HTTPS $ref resolution. This is useful for specifications that reference external schemas via URLs. HTTP resolution is opt-in for security (prevents SSRF attacks).
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
// Enable HTTP reference resolution (opt-in for security)
result, err := parser.ParseWithOptions(
parser.WithFilePath("spec-with-http-refs.yaml"),
parser.WithResolveRefs(true),
parser.WithResolveHTTPRefs(true), // Enable HTTP $ref resolution
// parser.WithInsecureSkipVerify(true), // For self-signed certs (dev only)
)
if err != nil {
log.Fatalf("failed to parse: %v", err)
}
fmt.Printf("Version: %s\n", result.Version)
fmt.Printf("Errors: %d\n", len(result.Errors))
// HTTP responses are cached, size-limited, and protected against circular refs
}
Example (ParseWithRefs) ¶
Example_parseWithRefs demonstrates parsing with external 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 (ReusableParser) ¶
Example_reusableParser demonstrates creating a reusable parser instance for processing multiple files with the same configuration.
package main
import (
"fmt"
"log"
"github.com/erraggy/oastools/parser"
)
func main() {
// Configure parser once
p := parser.New()
p.ResolveRefs = true
p.ValidateStructure = true
p.ResolveHTTPRefs = false // Keep HTTP refs disabled for security
// Parse multiple files with same config
files := []string{
"../testdata/petstore-3.0.yaml",
"../testdata/petstore-2.0.yaml",
}
for _, file := range files {
result, err := p.Parse(file)
if err != nil {
log.Printf("Error parsing %s: %v", file, err)
continue
}
fmt.Printf("%s: version=%s, errors=%d\n",
file, result.Version, len(result.Errors))
}
}
Index ¶
- Constants
- func FormatBytes(bytes int64) string
- func GetOAS2Operations(pathItem *PathItem) map[string]*Operationdeprecated
- func GetOAS3Operations(pathItem *PathItem) map[string]*Operationdeprecated
- func GetOAS32Operations(pathItem *PathItem) map[string]*Operationdeprecated
- func GetOperations(pathItem *PathItem, version OASVersion) map[string]*Operation
- type Callback
- type Components
- type Contact
- type Discriminator
- type DocumentStats
- type Encoding
- type Example
- type ExternalDocs
- type HTTPFetcher
- 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 Option
- func WithBytes(data []byte) Option
- func WithFilePath(path string) Option
- func WithInsecureSkipVerify(enabled bool) Option
- func WithReader(r io.Reader) Option
- func WithResolveHTTPRefs(enabled bool) Option
- func WithResolveRefs(enabled bool) Option
- func WithUserAgent(ua string) Option
- func WithValidateStructure(enabled bool) Option
- type Parameter
- type ParseResult
- type Parser
- type PathItem
- type Paths
- type RefResolver
- func (r *RefResolver) Resolve(doc map[string]any, ref string) (any, error)
- func (r *RefResolver) ResolveAllRefs(doc map[string]any) error
- func (r *RefResolver) ResolveExternal(ref string) (any, error)
- func (r *RefResolver) ResolveHTTP(ref string) (any, error)
- func (r *RefResolver) ResolveLocal(doc map[string]any, ref string) (any, error)
- type Reference
- type RequestBody
- type Response
- type Responses
- type Schema
- type SecurityRequirement
- type SecurityScheme
- type Server
- type ServerVariable
- type SourceFormat
- 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 ¶
func FormatBytes ¶ added in v1.9.2
FormatBytes formats a byte count into a human-readable string using binary units (KiB, MiB, etc.)
func GetOAS2Operations
deprecated
added in
v1.6.0
GetOAS2Operations extracts a map of all operations from a PathItem. Returns a map with keys for HTTP methods (get, put, post, delete, options, head, patch) and values pointing to the corresponding Operation (or nil if not defined). This is used for OAS 2.0 paths that do not support the TRACE method.
Deprecated: Use GetOperations(pathItem, OASVersion20) instead.
func GetOAS3Operations
deprecated
added in
v1.6.0
GetOAS3Operations extracts a map of all operations from a PathItem. Returns a map with keys for HTTP methods (get, put, post, delete, options, head, patch, trace) and values pointing to the corresponding Operation (or nil if not defined). This is used for OAS 3.0 and 3.1 paths that support the TRACE method but not QUERY.
Deprecated: Use GetOperations(pathItem, version) instead where version is OASVersion300 through OASVersion312.
func GetOAS32Operations
deprecated
added in
v1.15.2
GetOAS32Operations extracts a map of all operations from a PathItem. Returns a map with keys for HTTP methods including QUERY. This is used for OAS 3.2+ paths that support the QUERY method.
Deprecated: Use GetOperations(pathItem, OASVersion320) instead.
func GetOperations ¶ added in v1.15.2
func GetOperations(pathItem *PathItem, version OASVersion) map[string]*Operation
GetOperations extracts a map of all operations from a PathItem based on the OAS version. Returns a map with keys for HTTP methods and values pointing to the corresponding Operation (or nil if not defined). The returned map includes methods supported by the specified OAS version:
- OAS 2.0: get, put, post, delete, options, head, patch
- OAS 3.0-3.1: get, put, post, delete, options, head, patch, trace
- OAS 3.2+: get, put, post, delete, options, head, patch, trace, query
Types ¶
type Components ¶
type Components struct {
Schemas map[string]*Schema `yaml:"schemas,omitempty" json:"schemas,omitempty"`
Responses map[string]*Response `yaml:"responses,omitempty" json:"responses,omitempty"`
Parameters map[string]*Parameter `yaml:"parameters,omitempty" json:"parameters,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty" json:"examples,omitempty"`
RequestBodies map[string]*RequestBody `yaml:"requestBodies,omitempty" json:"requestBodies,omitempty"`
Headers map[string]*Header `yaml:"headers,omitempty" json:"headers,omitempty"`
SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty" json:"securitySchemes,omitempty"`
Links map[string]*Link `yaml:"links,omitempty" json:"links,omitempty"`
Callbacks map[string]*Callback `yaml:"callbacks,omitempty" json:"callbacks,omitempty"`
// OAS 3.1+ additions
PathItems map[string]*PathItem `yaml:"pathItems,omitempty" json:"pathItems,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Components holds reusable objects for different aspects of the OAS (OAS 3.0+)
func (*Components) MarshalJSON ¶ added in v1.6.1
func (c *Components) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for Components. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Components) UnmarshalJSON ¶ added in v1.6.1
func (c *Components) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for Components. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Contact ¶
type Contact struct {
Name string `yaml:"name,omitempty" json:"name,omitempty"`
URL string `yaml:"url,omitempty" json:"url,omitempty"`
Email string `yaml:"email,omitempty" json:"email,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Contact information for the exposed API
func (*Contact) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Contact. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Contact) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Contact. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Discriminator ¶
type Discriminator struct {
PropertyName string `yaml:"propertyName" json:"propertyName"`
Mapping map[string]string `yaml:"mapping,omitempty" json:"mapping,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
Discriminator represents a discriminator for polymorphism (OAS 3.0+)
func (*Discriminator) MarshalJSON ¶ added in v1.6.1
func (d *Discriminator) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for Discriminator. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Discriminator) UnmarshalJSON ¶ added in v1.6.1
func (d *Discriminator) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for Discriminator. This captures unknown fields (specification extensions like x-*) in the Extra map.
type DocumentStats ¶ added in v1.11.0
type DocumentStats struct {
PathCount int // Number of paths defined
OperationCount int // Total number of operations across all paths
SchemaCount int // Number of schemas/definitions
}
DocumentStats contains statistical information about an OAS document
func GetDocumentStats ¶ added in v1.11.0
func GetDocumentStats(doc any) DocumentStats
GetDocumentStats returns statistics for a parsed OAS document
type Encoding ¶
type Encoding struct {
ContentType string `yaml:"contentType,omitempty" json:"contentType,omitempty"`
Headers map[string]*Header `yaml:"headers,omitempty" json:"headers,omitempty"`
Style string `yaml:"style,omitempty" json:"style,omitempty"`
Explode *bool `yaml:"explode,omitempty" json:"explode,omitempty"`
AllowReserved bool `yaml:"allowReserved,omitempty" json:"allowReserved,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Encoding defines encoding for a specific property (OAS 3.0+)
func (*Encoding) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Encoding. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Encoding) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Encoding. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Example ¶
type Example struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Value any `yaml:"value,omitempty" json:"value,omitempty"`
ExternalValue string `yaml:"externalValue,omitempty" json:"externalValue,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Example represents an example object (OAS 3.0+)
func (*Example) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Example. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Example) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Example. This captures unknown fields (specification extensions like x-*) in the Extra map.
type ExternalDocs ¶
type ExternalDocs struct {
Description string `yaml:"description,omitempty" json:"description,omitempty"`
URL string `yaml:"url" json:"url"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
ExternalDocs allows referencing external documentation
func (*ExternalDocs) MarshalJSON ¶ added in v1.6.1
func (e *ExternalDocs) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for ExternalDocs. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*ExternalDocs) UnmarshalJSON ¶ added in v1.6.1
func (e *ExternalDocs) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for ExternalDocs. This captures unknown fields (specification extensions like x-*) in the Extra map.
type HTTPFetcher ¶ added in v1.18.0
HTTPFetcher is a function type for fetching content from HTTP/HTTPS URLs Returns the response body, content-type header, and any error
type Header ¶
type Header struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Required bool `yaml:"required,omitempty" json:"required,omitempty"`
Deprecated bool `yaml:"deprecated,omitempty" json:"deprecated,omitempty"` // OAS 3.0+
// OAS 3.0+ fields
Style string `yaml:"style,omitempty" json:"style,omitempty"`
Explode *bool `yaml:"explode,omitempty" json:"explode,omitempty"`
Schema *Schema `yaml:"schema,omitempty" json:"schema,omitempty"`
Example any `yaml:"example,omitempty" json:"example,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty" json:"examples,omitempty"`
Content map[string]*MediaType `yaml:"content,omitempty" json:"content,omitempty"`
// OAS 2.0 fields
Type string `yaml:"type,omitempty" json:"type,omitempty"` // OAS 2.0
Format string `yaml:"format,omitempty" json:"format,omitempty"` // OAS 2.0
Items *Items `yaml:"items,omitempty" json:"items,omitempty"` // OAS 2.0
CollectionFormat string `yaml:"collectionFormat,omitempty" json:"collectionFormat,omitempty"` // OAS 2.0
Default any `yaml:"default,omitempty" json:"default,omitempty"` // OAS 2.0
Maximum *float64 `yaml:"maximum,omitempty" json:"maximum,omitempty"` // OAS 2.0
ExclusiveMaximum bool `yaml:"exclusiveMaximum,omitempty" json:"exclusiveMaximum,omitempty"` // OAS 2.0
Minimum *float64 `yaml:"minimum,omitempty" json:"minimum,omitempty"` // OAS 2.0
ExclusiveMinimum bool `yaml:"exclusiveMinimum,omitempty" json:"exclusiveMinimum,omitempty"` // OAS 2.0
MaxLength *int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"` // OAS 2.0
MinLength *int `yaml:"minLength,omitempty" json:"minLength,omitempty"` // OAS 2.0
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"` // OAS 2.0
MaxItems *int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"` // OAS 2.0
MinItems *int `yaml:"minItems,omitempty" json:"minItems,omitempty"` // OAS 2.0
UniqueItems bool `yaml:"uniqueItems,omitempty" json:"uniqueItems,omitempty"` // OAS 2.0
Enum []any `yaml:"enum,omitempty" json:"enum,omitempty"` // OAS 2.0
MultipleOf *float64 `yaml:"multipleOf,omitempty" json:"multipleOf,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Header represents a header object
func (*Header) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Header. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Header) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Header. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Info ¶
type Info struct {
Title string `yaml:"title" json:"title"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
TermsOfService string `yaml:"termsOfService,omitempty" json:"termsOfService,omitempty"`
Contact *Contact `yaml:"contact,omitempty" json:"contact,omitempty"`
License *License `yaml:"license,omitempty" json:"license,omitempty"`
Version string `yaml:"version" json:"version"`
// OAS 3.1+ additions
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
// and any other fields not explicitly defined in the struct
Extra map[string]any `yaml:",inline" json:"-"`
}
Info provides metadata about the API Common across all OAS versions (2.0, 3.0, 3.1, 3.2)
func (*Info) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Info. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Info) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Info. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Items ¶
type Items struct {
Type string `yaml:"type" json:"type"`
Format string `yaml:"format,omitempty" json:"format,omitempty"`
Items *Items `yaml:"items,omitempty" json:"items,omitempty"`
CollectionFormat string `yaml:"collectionFormat,omitempty" json:"collectionFormat,omitempty"`
Default any `yaml:"default,omitempty" json:"default,omitempty"`
Maximum *float64 `yaml:"maximum,omitempty" json:"maximum,omitempty"`
ExclusiveMaximum bool `yaml:"exclusiveMaximum,omitempty" json:"exclusiveMaximum,omitempty"`
Minimum *float64 `yaml:"minimum,omitempty" json:"minimum,omitempty"`
ExclusiveMinimum bool `yaml:"exclusiveMinimum,omitempty" json:"exclusiveMinimum,omitempty"`
MaxLength *int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"`
MinLength *int `yaml:"minLength,omitempty" json:"minLength,omitempty"`
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"`
MaxItems *int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"`
MinItems *int `yaml:"minItems,omitempty" json:"minItems,omitempty"`
UniqueItems bool `yaml:"uniqueItems,omitempty" json:"uniqueItems,omitempty"`
Enum []any `yaml:"enum,omitempty" json:"enum,omitempty"`
MultipleOf *float64 `yaml:"multipleOf,omitempty" json:"multipleOf,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
Items represents items object for array parameters (OAS 2.0)
func (*Items) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Items. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Items) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Items. This captures unknown fields (specification extensions like x-*) in the Extra map.
type License ¶
type License struct {
Name string `yaml:"name" json:"name"`
URL string `yaml:"url,omitempty" json:"url,omitempty"`
Identifier string `yaml:"identifier,omitempty" json:"identifier,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
License information for the exposed API
func (*License) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for License. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*License) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for License. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Link ¶
type Link struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
OperationRef string `yaml:"operationRef,omitempty" json:"operationRef,omitempty"`
OperationID string `yaml:"operationId,omitempty" json:"operationId,omitempty"`
Parameters map[string]any `yaml:"parameters,omitempty" json:"parameters,omitempty"`
RequestBody any `yaml:"requestBody,omitempty" json:"requestBody,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Server *Server `yaml:"server,omitempty" json:"server,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Link represents a possible design-time link for a response (OAS 3.0+)
func (*Link) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Link. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Link) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Link. This captures unknown fields (specification extensions like x-*) in the Extra map.
type MediaType ¶
type MediaType struct {
Schema *Schema `yaml:"schema,omitempty" json:"schema,omitempty"`
Example any `yaml:"example,omitempty" json:"example,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty" json:"examples,omitempty"`
Encoding map[string]*Encoding `yaml:"encoding,omitempty" json:"encoding,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
MediaType provides schema and examples for the media type (OAS 3.0+)
func (*MediaType) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for MediaType. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*MediaType) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for MediaType. This captures unknown fields (specification extensions like x-*) in the Extra map.
type OAS2Document ¶
type OAS2Document struct {
Swagger string `yaml:"swagger" json:"swagger"` // Required: "2.0"
Info *Info `yaml:"info" json:"info"` // Required
Host string `yaml:"host,omitempty" json:"host,omitempty"`
BasePath string `yaml:"basePath,omitempty" json:"basePath,omitempty"`
Schemes []string `yaml:"schemes,omitempty" json:"schemes,omitempty"` // e.g., ["http", "https"]
Consumes []string `yaml:"consumes,omitempty" json:"consumes,omitempty"`
Produces []string `yaml:"produces,omitempty" json:"produces,omitempty"`
Paths Paths `yaml:"paths" json:"paths"` // Required
Definitions map[string]*Schema `yaml:"definitions,omitempty" json:"definitions,omitempty"`
Parameters map[string]*Parameter `yaml:"parameters,omitempty" json:"parameters,omitempty"`
Responses map[string]*Response `yaml:"responses,omitempty" json:"responses,omitempty"`
SecurityDefinitions map[string]*SecurityScheme `yaml:"securityDefinitions,omitempty" json:"securityDefinitions,omitempty"`
Security []SecurityRequirement `yaml:"security,omitempty" json:"security,omitempty"`
Tags []*Tag `yaml:"tags,omitempty" json:"tags,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty" json:"externalDocs,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
OASVersion OASVersion `yaml:"-" json:"-"`
}
OAS2Document represents an OpenAPI Specification 2.0 (Swagger) document Reference: https://spec.openapis.org/oas/v2.0.html
func (*OAS2Document) MarshalJSON ¶ added in v1.6.1
func (d *OAS2Document) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for OAS2Document. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline". The Extra map is merged after marshaling the base struct to ensure specification extensions appear at the root level.
func (*OAS2Document) UnmarshalJSON ¶ added in v1.6.1
func (d *OAS2Document) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for OAS2Document. This captures unknown fields (specification extensions like x-*) in the Extra map. It unmarshals known fields using the standard decoder, then identifies and stores any fields not defined in the OAS 2.0 specification in the Extra map.
type OAS3Document ¶
type OAS3Document struct {
OpenAPI string `yaml:"openapi" json:"openapi"` // Required: "3.0.x", "3.1.x", or "3.2.x"
Info *Info `yaml:"info" json:"info"` // Required
Servers []*Server `yaml:"servers,omitempty" json:"servers,omitempty"`
Paths Paths `yaml:"paths,omitempty" json:"paths,omitempty"` // Required in 3.0, optional in 3.1+
Webhooks map[string]*PathItem `yaml:"webhooks,omitempty" json:"webhooks,omitempty"` // OAS 3.1+
Components *Components `yaml:"components,omitempty" json:"components,omitempty"`
Security []SecurityRequirement `yaml:"security,omitempty" json:"security,omitempty"`
Tags []*Tag `yaml:"tags,omitempty" json:"tags,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty" json:"externalDocs,omitempty"`
OASVersion OASVersion `yaml:"-" json:"-"`
// OAS 3.1+ additions
JSONSchemaDialect string `yaml:"jsonSchemaDialect,omitempty" json:"jsonSchemaDialect,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
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
func (*OAS3Document) MarshalJSON ¶ added in v1.6.1
func (d *OAS3Document) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for OAS3Document. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*OAS3Document) UnmarshalJSON ¶ added in v1.6.1
func (d *OAS3Document) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for OAS3Document. This captures unknown fields (specification extensions like x-*) in the Extra map.
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" json:"authorizationUrl,omitempty"`
TokenURL string `yaml:"tokenUrl,omitempty" json:"tokenUrl,omitempty"`
RefreshURL string `yaml:"refreshUrl,omitempty" json:"refreshUrl,omitempty"`
Scopes map[string]string `yaml:"scopes" json:"scopes"`
Extra map[string]any `yaml:",inline" json:"-"`
}
OAuthFlow represents configuration for a single OAuth flow (OAS 3.0+)
func (*OAuthFlow) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for OAuthFlow. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*OAuthFlow) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for OAuthFlow. This captures unknown fields (specification extensions like x-*) in the Extra map.
type OAuthFlows ¶
type OAuthFlows struct {
Implicit *OAuthFlow `yaml:"implicit,omitempty" json:"implicit,omitempty"`
Password *OAuthFlow `yaml:"password,omitempty" json:"password,omitempty"`
ClientCredentials *OAuthFlow `yaml:"clientCredentials,omitempty" json:"clientCredentials,omitempty"`
AuthorizationCode *OAuthFlow `yaml:"authorizationCode,omitempty" json:"authorizationCode,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
OAuthFlows allows configuration of the supported OAuth Flows (OAS 3.0+)
func (*OAuthFlows) MarshalJSON ¶ added in v1.6.1
func (of *OAuthFlows) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for OAuthFlows. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*OAuthFlows) UnmarshalJSON ¶ added in v1.6.1
func (of *OAuthFlows) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for OAuthFlows. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Operation ¶
type Operation struct {
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty" json:"externalDocs,omitempty"`
OperationID string `yaml:"operationId,omitempty" json:"operationId,omitempty"`
Parameters []*Parameter `yaml:"parameters,omitempty" json:"parameters,omitempty"`
RequestBody *RequestBody `yaml:"requestBody,omitempty" json:"requestBody,omitempty"` // OAS 3.0+
Responses *Responses `yaml:"responses" json:"responses"`
Callbacks map[string]*Callback `yaml:"callbacks,omitempty" json:"callbacks,omitempty"` // OAS 3.0+
Deprecated bool `yaml:"deprecated,omitempty" json:"deprecated,omitempty"`
Security []SecurityRequirement `yaml:"security,omitempty" json:"security,omitempty"`
Servers []*Server `yaml:"servers,omitempty" json:"servers,omitempty"` // OAS 3.0+
// OAS 2.0 specific
Consumes []string `yaml:"consumes,omitempty" json:"consumes,omitempty"` // OAS 2.0
Produces []string `yaml:"produces,omitempty" json:"produces,omitempty"` // OAS 2.0
Schemes []string `yaml:"schemes,omitempty" json:"schemes,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Operation describes a single API operation on a path
func (*Operation) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Operation. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Operation) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Operation. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Option ¶ added in v1.11.0
type Option func(*parseConfig) error
Option is a function that configures a parse operation
func WithFilePath ¶ added in v1.11.0
WithFilePath specifies a file path or URL as the input source
func WithInsecureSkipVerify ¶ added in v1.18.0
WithInsecureSkipVerify disables TLS certificate verification for HTTPS refs Use with caution - only enable for testing or internal servers with self-signed certs Note: This option only takes effect when ResolveHTTPRefs is also enabled
func WithReader ¶ added in v1.11.0
WithReader specifies an io.Reader as the input source
func WithResolveHTTPRefs ¶ added in v1.18.0
WithResolveHTTPRefs enables resolution of HTTP/HTTPS $ref URLs This is disabled by default for security (SSRF protection) Must be explicitly enabled when parsing specifications with HTTP refs Note: This option only takes effect when ResolveRefs is also enabled
func WithResolveRefs ¶ added in v1.11.0
WithResolveRefs enables or disables reference resolution ($ref) Default: false
func WithUserAgent ¶ added in v1.11.0
WithUserAgent sets the User-Agent string for HTTP requests Default: "oastools/vX.Y.Z"
func WithValidateStructure ¶ added in v1.11.0
WithValidateStructure enables or disables basic structure validation Default: true
type Parameter ¶
type Parameter struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
Name string `yaml:"name" json:"name"`
In string `yaml:"in" json:"in"` // "query", "header", "path", "cookie" (OAS 3.0+), "formData", "body" (OAS 2.0)
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Required bool `yaml:"required,omitempty" json:"required,omitempty"`
Deprecated bool `yaml:"deprecated,omitempty" json:"deprecated,omitempty"` // OAS 3.0+
// OAS 3.0+ fields
Style string `yaml:"style,omitempty" json:"style,omitempty"`
Explode *bool `yaml:"explode,omitempty" json:"explode,omitempty"`
AllowReserved bool `yaml:"allowReserved,omitempty" json:"allowReserved,omitempty"`
Schema *Schema `yaml:"schema,omitempty" json:"schema,omitempty"`
Example any `yaml:"example,omitempty" json:"example,omitempty"`
Examples map[string]*Example `yaml:"examples,omitempty" json:"examples,omitempty"`
Content map[string]*MediaType `yaml:"content,omitempty" json:"content,omitempty"`
// OAS 2.0 fields
Type string `yaml:"type,omitempty" json:"type,omitempty"` // OAS 2.0
Format string `yaml:"format,omitempty" json:"format,omitempty"` // OAS 2.0
AllowEmptyValue bool `yaml:"allowEmptyValue,omitempty" json:"allowEmptyValue,omitempty"` // OAS 2.0
Items *Items `yaml:"items,omitempty" json:"items,omitempty"` // OAS 2.0
CollectionFormat string `yaml:"collectionFormat,omitempty" json:"collectionFormat,omitempty"` // OAS 2.0
Default any `yaml:"default,omitempty" json:"default,omitempty"` // OAS 2.0
Maximum *float64 `yaml:"maximum,omitempty" json:"maximum,omitempty"` // OAS 2.0
ExclusiveMaximum bool `yaml:"exclusiveMaximum,omitempty" json:"exclusiveMaximum,omitempty"` // OAS 2.0
Minimum *float64 `yaml:"minimum,omitempty" json:"minimum,omitempty"` // OAS 2.0
ExclusiveMinimum bool `yaml:"exclusiveMinimum,omitempty" json:"exclusiveMinimum,omitempty"` // OAS 2.0
MaxLength *int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"` // OAS 2.0
MinLength *int `yaml:"minLength,omitempty" json:"minLength,omitempty"` // OAS 2.0
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"` // OAS 2.0
MaxItems *int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"` // OAS 2.0
MinItems *int `yaml:"minItems,omitempty" json:"minItems,omitempty"` // OAS 2.0
UniqueItems bool `yaml:"uniqueItems,omitempty" json:"uniqueItems,omitempty"` // OAS 2.0
Enum []any `yaml:"enum,omitempty" json:"enum,omitempty"` // OAS 2.0
MultipleOf *float64 `yaml:"multipleOf,omitempty" json:"multipleOf,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Parameter describes a single operation parameter
func (*Parameter) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Parameter. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Parameter) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Parameter. This captures unknown fields (specification extensions like x-*) in the Extra map.
type ParseResult ¶
type ParseResult struct {
// SourcePath is the document's input source path that it was read from.
// Note: if the source was not a file path, this will be set to the name of the method
// and end in '.yaml' or '.json' based on the detected format
SourcePath string
// SourceFormat is the format of the source file (JSON or YAML)
SourceFormat SourceFormat
// 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]any
// Document contains the version-specific parsed document:
// - *OAS2Document for OpenAPI 2.0
// - *OAS3Document for OpenAPI 3.x
Document any
// 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
// LoadTime is the time taken to load the source data (file, URL, etc.)
LoadTime time.Duration
// SourceSize is the size of the source data in bytes
SourceSize int64
// Stats contains statistical information about the document
Stats DocumentStats
}
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.
Immutability ¶
While Go does not enforce immutability, callers should treat ParseResult as read-only after parsing. Modifying the returned document may lead to unexpected behavior if the document is cached or shared across multiple operations.
For document modification use cases:
- Version conversion: Use the converter package
- Document merging: Use the joiner package
- Manual modification: Create a deep copy first using Copy() method
Example of safe modification:
original, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))
modified := original.Copy() // Deep copy
// Now safe to modify 'modified' without affecting 'original'
func ParseWithOptions ¶ added in v1.11.0
func ParseWithOptions(opts ...Option) (*ParseResult, error)
ParseWithOptions parses 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 := parser.ParseWithOptions(
parser.WithFilePath("openapi.yaml"),
parser.WithResolveRefs(true),
)
func (*ParseResult) Copy ¶ added in v1.11.1
func (pr *ParseResult) Copy() *ParseResult
Copy creates a deep copy of the ParseResult, including all nested documents and data. This is useful when you need to modify a parsed document without affecting the original.
The deep copy is performed using JSON marshaling and unmarshaling to ensure all nested structures and maps are properly copied.
Example:
original, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))
modified := original.Copy()
// Modify the copy without affecting the original
if doc, ok := modified.Document.(*parser.OAS3Document); ok {
doc.Info.Title = "Modified API"
}
type Parser ¶
type Parser struct {
// ResolveRefs determines whether to resolve $ref references
ResolveRefs bool
// ResolveHTTPRefs determines whether to resolve HTTP/HTTPS $ref URLs
// This is disabled by default for security (SSRF protection)
// Must be explicitly enabled when parsing specifications with HTTP refs
ResolveHTTPRefs bool
// InsecureSkipVerify disables TLS certificate verification for HTTP refs
// Use with caution - only enable for testing or internal servers with self-signed certs
InsecureSkipVerify bool
// ValidateStructure determines whether to perform basic structure validation
ValidateStructure bool
// UserAgent is the User-Agent string used when fetching URLs
// Defaults to "oastools" if not set
UserAgent string
}
Parser handles OpenAPI specification parsing
func (*Parser) Parse ¶
func (p *Parser) Parse(specPath string) (*ParseResult, error)
Parse parses an OpenAPI specification file or URL For URLs (http:// or https://), the content is fetched and parsed For local files, the file is read and parsed
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 Note: since there is no actual ParseResult.SourcePath, it will be set to: ParseBytes.yaml or ParseBytes.json
func (*Parser) ParseReader ¶
func (p *Parser) ParseReader(r io.Reader) (*ParseResult, error)
ParseReader parses an OpenAPI specification from an io.Reader Note: since there is no actual ParseResult.SourcePath, it will be set to: ParseReader.yaml or ParseReader.json
type PathItem ¶
type PathItem struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"` // OAS 3.0+
Description string `yaml:"description,omitempty" json:"description,omitempty"` // OAS 3.0+
Get *Operation `yaml:"get,omitempty" json:"get,omitempty"`
Put *Operation `yaml:"put,omitempty" json:"put,omitempty"`
Post *Operation `yaml:"post,omitempty" json:"post,omitempty"`
Delete *Operation `yaml:"delete,omitempty" json:"delete,omitempty"`
Options *Operation `yaml:"options,omitempty" json:"options,omitempty"`
Head *Operation `yaml:"head,omitempty" json:"head,omitempty"`
Patch *Operation `yaml:"patch,omitempty" json:"patch,omitempty"`
Trace *Operation `yaml:"trace,omitempty" json:"trace,omitempty"` // OAS 3.0+
Query *Operation `yaml:"query,omitempty" json:"query,omitempty"` // OAS 3.2+
Servers []*Server `yaml:"servers,omitempty" json:"servers,omitempty"` // OAS 3.0+
Parameters []*Parameter `yaml:"parameters,omitempty" json:"parameters,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
PathItem describes the operations available on a single path
func (*PathItem) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for PathItem. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*PathItem) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for PathItem. This captures unknown fields (specification extensions like x-*) in the Extra map.
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 for local and file-based refs
func NewRefResolverWithHTTP ¶ added in v1.18.0
func NewRefResolverWithHTTP(baseDir, baseURL string, fetcher HTTPFetcher) *RefResolver
NewRefResolverWithHTTP creates a reference resolver with HTTP/HTTPS support The baseURL is used for resolving relative refs when the source is an HTTP URL The fetcher function is called to retrieve content from HTTP/HTTPS URLs
func (*RefResolver) ResolveAllRefs ¶
func (r *RefResolver) ResolveAllRefs(doc map[string]any) error
ResolveAllRefs walks through the entire document and resolves all $ref references
func (*RefResolver) ResolveExternal ¶
func (r *RefResolver) ResolveExternal(ref string) (any, 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) ResolveHTTP ¶ added in v1.18.0
func (r *RefResolver) ResolveHTTP(ref string) (any, error)
ResolveHTTP resolves HTTP/HTTPS URL references HTTP refs are in the format: https://example.com/api.yaml#/components/schemas/Pet
func (*RefResolver) ResolveLocal ¶
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" json:"$ref"`
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"` // OAS 3.1+
Description string `yaml:"description,omitempty" json:"description,omitempty"` // OAS 3.1+
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Reference represents a JSON Reference ($ref)
func (*Reference) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Reference. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Reference) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Reference. This captures unknown fields (specification extensions like x-*) in the Extra map.
type RequestBody ¶
type RequestBody struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Content map[string]*MediaType `yaml:"content" json:"content"`
Required bool `yaml:"required,omitempty" json:"required,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
RequestBody describes a single request body (OAS 3.0+)
func (*RequestBody) MarshalJSON ¶ added in v1.6.1
func (rb *RequestBody) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for RequestBody. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*RequestBody) UnmarshalJSON ¶ added in v1.6.1
func (rb *RequestBody) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for RequestBody. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Response ¶
type Response struct {
Ref string `yaml:"$ref,omitempty" json:"$ref,omitempty"`
Description string `yaml:"description" json:"description"`
Headers map[string]*Header `yaml:"headers,omitempty" json:"headers,omitempty"`
Content map[string]*MediaType `yaml:"content,omitempty" json:"content,omitempty"` // OAS 3.0+
Links map[string]*Link `yaml:"links,omitempty" json:"links,omitempty"` // OAS 3.0+
// OAS 2.0 specific
Schema *Schema `yaml:"schema,omitempty" json:"schema,omitempty"` // OAS 2.0
Examples map[string]any `yaml:"examples,omitempty" json:"examples,omitempty"` // OAS 2.0
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Response describes a single response from an API Operation
func (*Response) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Response. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Response) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Response. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Responses ¶
type Responses struct {
Default *Response `yaml:"default,omitempty" json:"default,omitempty"`
Codes map[string]*Response `yaml:",inline" json:"-"` // Handled by custom marshaler
}
Responses is a container for the expected responses of an operation
func (*Responses) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Responses. This flattens the Codes map into the top-level JSON object, where each HTTP status code (e.g., "200", "404") or wildcard pattern (e.g., "2XX") becomes a direct field in the JSON output. The "default" response is also included at the top level if present.
func (*Responses) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Responses. This captures status code fields in the Codes map and validates that each status code is either a valid HTTP status code (e.g., "200", "404"), a wildcard pattern (e.g., "2XX"), or a specification extension (e.g., "x-custom"). Returns an error if an invalid status code is encountered.
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" json:"$ref,omitempty"`
Schema string `yaml:"$schema,omitempty" json:"$schema,omitempty"` // JSON Schema Draft version
// Metadata
Title string `yaml:"title,omitempty" json:"title,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Default any `yaml:"default,omitempty" json:"default,omitempty"`
Examples []any `yaml:"examples,omitempty" json:"examples,omitempty"` // OAS 3.0+, JSON Schema Draft 2020-12
// Type validation
Type any `yaml:"type,omitempty" json:"type,omitempty"` // string or []string (OAS 3.1+)
Enum []any `yaml:"enum,omitempty" json:"enum,omitempty"`
Const any `yaml:"const,omitempty" json:"const,omitempty"` // JSON Schema Draft 2020-12
// Numeric validation
MultipleOf *float64 `yaml:"multipleOf,omitempty" json:"multipleOf,omitempty"`
Maximum *float64 `yaml:"maximum,omitempty" json:"maximum,omitempty"`
ExclusiveMaximum any `yaml:"exclusiveMaximum,omitempty" json:"exclusiveMaximum,omitempty"` // bool in OAS 2.0/3.0, number in 3.1+
Minimum *float64 `yaml:"minimum,omitempty" json:"minimum,omitempty"`
ExclusiveMinimum any `yaml:"exclusiveMinimum,omitempty" json:"exclusiveMinimum,omitempty"` // bool in OAS 2.0/3.0, number in 3.1+
// String validation
MaxLength *int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"`
MinLength *int `yaml:"minLength,omitempty" json:"minLength,omitempty"`
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"`
// Array validation
Items any `yaml:"items,omitempty" json:"items,omitempty"` // *Schema or bool (OAS 3.1+)
PrefixItems []*Schema `yaml:"prefixItems,omitempty" json:"prefixItems,omitempty"` // JSON Schema Draft 2020-12
AdditionalItems any `yaml:"additionalItems,omitempty" json:"additionalItems,omitempty"` // *Schema or bool
MaxItems *int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"`
MinItems *int `yaml:"minItems,omitempty" json:"minItems,omitempty"`
UniqueItems bool `yaml:"uniqueItems,omitempty" json:"uniqueItems,omitempty"`
Contains *Schema `yaml:"contains,omitempty" json:"contains,omitempty"` // JSON Schema Draft 2020-12
MaxContains *int `yaml:"maxContains,omitempty" json:"maxContains,omitempty"` // JSON Schema Draft 2020-12
MinContains *int `yaml:"minContains,omitempty" json:"minContains,omitempty"` // JSON Schema Draft 2020-12
// Object validation
Properties map[string]*Schema `yaml:"properties,omitempty" json:"properties,omitempty"`
PatternProperties map[string]*Schema `yaml:"patternProperties,omitempty" json:"patternProperties,omitempty"`
AdditionalProperties any `yaml:"additionalProperties,omitempty" json:"additionalProperties,omitempty"` // *Schema or bool
Required []string `yaml:"required,omitempty" json:"required,omitempty"`
PropertyNames *Schema `yaml:"propertyNames,omitempty" json:"propertyNames,omitempty"` // JSON Schema Draft 2020-12
MaxProperties *int `yaml:"maxProperties,omitempty" json:"maxProperties,omitempty"`
MinProperties *int `yaml:"minProperties,omitempty" json:"minProperties,omitempty"`
DependentRequired map[string][]string `yaml:"dependentRequired,omitempty" json:"dependentRequired,omitempty"` // JSON Schema Draft 2020-12
DependentSchemas map[string]*Schema `yaml:"dependentSchemas,omitempty" json:"dependentSchemas,omitempty"` // JSON Schema Draft 2020-12
// Conditional schemas
If *Schema `yaml:"if,omitempty" json:"if,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
Then *Schema `yaml:"then,omitempty" json:"then,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
Else *Schema `yaml:"else,omitempty" json:"else,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
// Schema composition
AllOf []*Schema `yaml:"allOf,omitempty" json:"allOf,omitempty"`
AnyOf []*Schema `yaml:"anyOf,omitempty" json:"anyOf,omitempty"`
OneOf []*Schema `yaml:"oneOf,omitempty" json:"oneOf,omitempty"`
Not *Schema `yaml:"not,omitempty" json:"not,omitempty"`
// OAS specific extensions
Nullable bool `yaml:"nullable,omitempty" json:"nullable,omitempty"` // OAS 3.0 only (replaced by type: [T, "null"] in 3.1+)
Discriminator *Discriminator `yaml:"discriminator,omitempty" json:"discriminator,omitempty"` // OAS 3.0+
ReadOnly bool `yaml:"readOnly,omitempty" json:"readOnly,omitempty"` // OAS 2.0+
WriteOnly bool `yaml:"writeOnly,omitempty" json:"writeOnly,omitempty"` // OAS 3.0+
XML *XML `yaml:"xml,omitempty" json:"xml,omitempty"` // OAS 2.0+
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty" json:"externalDocs,omitempty"` // OAS 2.0+
Example any `yaml:"example,omitempty" json:"example,omitempty"` // OAS 2.0, 3.0 (deprecated in 3.1+)
Deprecated bool `yaml:"deprecated,omitempty" json:"deprecated,omitempty"` // OAS 3.0+
// Format
Format string `yaml:"format,omitempty" json:"format,omitempty"` // e.g., "date-time", "email", "uri", etc.
// OAS 2.0 specific
CollectionFormat string `yaml:"collectionFormat,omitempty" json:"collectionFormat,omitempty"` // OAS 2.0
// JSON Schema Draft 2020-12 additional fields
ID string `yaml:"$id,omitempty" json:"$id,omitempty"`
Anchor string `yaml:"$anchor,omitempty" json:"$anchor,omitempty"`
DynamicRef string `yaml:"$dynamicRef,omitempty" json:"$dynamicRef,omitempty"`
DynamicAnchor string `yaml:"$dynamicAnchor,omitempty" json:"$dynamicAnchor,omitempty"`
Vocabulary map[string]bool `yaml:"$vocabulary,omitempty" json:"$vocabulary,omitempty"`
Comment string `yaml:"$comment,omitempty" json:"$comment,omitempty"`
Defs map[string]*Schema `yaml:"$defs,omitempty" json:"$defs,omitempty"`
// Extension fields
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Schema represents a JSON Schema Supports OAS 2.0, OAS 3.0, OAS 3.1+ (JSON Schema Draft 2020-12)
func (*Schema) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Schema. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Schema) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Schema. This captures unknown fields (specification extensions like x-*) in the Extra map.
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" json:"$ref,omitempty"`
Type string `yaml:"type" json:"type"` // "apiKey", "http", "oauth2", "openIdConnect" (OAS 3.0+), "basic", "apiKey", "oauth2" (OAS 2.0)
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Type: apiKey (OAS 2.0+, 3.0+)
Name string `yaml:"name,omitempty" json:"name,omitempty"` // Header, query, or cookie parameter name
In string `yaml:"in,omitempty" json:"in,omitempty"` // "query", "header", "cookie" (OAS 3.0+)
// Type: http (OAS 3.0+)
Scheme string `yaml:"scheme,omitempty" json:"scheme,omitempty"` // e.g., "basic", "bearer"
BearerFormat string `yaml:"bearerFormat,omitempty" json:"bearerFormat,omitempty"` // e.g., "JWT"
// Type: oauth2
Flows *OAuthFlows `yaml:"flows,omitempty" json:"flows,omitempty"` // OAS 3.0+
// Type: oauth2 (OAS 2.0)
Flow string `yaml:"flow,omitempty" json:"flow,omitempty"` // "implicit", "password", "application", "accessCode"
AuthorizationURL string `yaml:"authorizationUrl,omitempty" json:"authorizationUrl,omitempty"` // OAS 2.0
TokenURL string `yaml:"tokenUrl,omitempty" json:"tokenUrl,omitempty"` // OAS 2.0
Scopes map[string]string `yaml:"scopes,omitempty" json:"scopes,omitempty"` // OAS 2.0
// Type: openIdConnect (OAS 3.0+)
OpenIDConnectURL string `yaml:"openIdConnectUrl,omitempty" json:"openIdConnectUrl,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
SecurityScheme defines a security scheme that can be used by the operations
func (*SecurityScheme) MarshalJSON ¶ added in v1.6.1
func (ss *SecurityScheme) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for SecurityScheme. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*SecurityScheme) UnmarshalJSON ¶ added in v1.6.1
func (ss *SecurityScheme) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for SecurityScheme. This captures unknown fields (specification extensions like x-*) in the Extra map.
type Server ¶
type Server struct {
URL string `yaml:"url" json:"url"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Variables map[string]ServerVariable `yaml:"variables,omitempty" json:"variables,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Server represents a Server object (OAS 3.0+)
func (*Server) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Server. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Server) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Server. This captures unknown fields (specification extensions like x-*) in the Extra map.
type ServerVariable ¶
type ServerVariable struct {
Enum []string `yaml:"enum,omitempty" json:"enum,omitempty"`
Default string `yaml:"default" json:"default"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
ServerVariable represents a Server Variable object (OAS 3.0+)
func (*ServerVariable) MarshalJSON ¶ added in v1.6.1
func (sv *ServerVariable) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for ServerVariable. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*ServerVariable) UnmarshalJSON ¶ added in v1.6.1
func (sv *ServerVariable) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for ServerVariable. This captures unknown fields (specification extensions like x-*) in the Extra map.
type SourceFormat ¶ added in v1.6.0
type SourceFormat string
SourceFormat represents the format of the source OpenAPI specification file
const ( // SourceFormatYAML indicates the source was in YAML format SourceFormatYAML SourceFormat = "yaml" // SourceFormatJSON indicates the source was in JSON format SourceFormatJSON SourceFormat = "json" // SourceFormatUnknown indicates the source format could not be determined SourceFormatUnknown SourceFormat = "unknown" )
type Tag ¶
type Tag struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty" json:"externalDocs,omitempty"`
// Extra captures specification extensions (fields starting with "x-")
Extra map[string]any `yaml:",inline" json:"-"`
}
Tag adds metadata to a single tag used by operations
func (*Tag) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for Tag. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*Tag) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for Tag. This captures unknown fields (specification extensions like x-*) in the Extra map.
type XML ¶
type XML struct {
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Namespace string `yaml:"namespace,omitempty" json:"namespace,omitempty"`
Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`
Attribute bool `yaml:"attribute,omitempty" json:"attribute,omitempty"`
Wrapped bool `yaml:"wrapped,omitempty" json:"wrapped,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
XML represents metadata for XML encoding (OAS 2.0+)
func (*XML) MarshalJSON ¶ added in v1.6.1
MarshalJSON implements custom JSON marshaling for XML. This is required to flatten Extra fields (specification extensions like x-*) into the top-level JSON object, as Go's encoding/json doesn't support inline maps like yaml:",inline".
func (*XML) UnmarshalJSON ¶ added in v1.6.1
UnmarshalJSON implements custom JSON unmarshaling for XML. This captures unknown fields (specification extensions like x-*) in the Extra map.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
jsonhelpers
Package jsonhelpers provides helper functions for JSON marshaling and unmarshaling with support for extension fields (x-* properties) in OpenAPI specifications.
|
Package jsonhelpers provides helper functions for JSON marshaling and unmarshaling with support for extension fields (x-* properties) in OpenAPI specifications. |