parser

package
v1.41.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: MIT Imports: 24 Imported by: 0

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 100 documents by default 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.

Circular Reference Handling

When the parser detects circular references during $ref resolution, it uses a "silent fallback" strategy: the affected $ref nodes remain unresolved, but parsing continues successfully. This ensures documents with circular references can still be used while maintaining safety.

Circular references are detected when:

  • A $ref points to an ancestor in the current resolution path
  • The resolution depth exceeds MaxRefDepth (default: 100)

When circular references are detected:

  • The $ref node is left unresolved (preserves the "$ref" key)
  • A warning is added to result.Warnings
  • The document remains valid for most operations

To check for circular reference warnings after parsing:

result, err := parser.ParseWithOptions(
	parser.WithFilePath("openapi.yaml"),
	parser.WithResolveRefs(true),
)
if err != nil {
	log.Fatal(err)
}
for _, warning := range result.Warnings {
	if strings.Contains(warning, "circular") {
		fmt.Println("Document contains circular references")
	}
}

Resource Limits

The parser enforces configurable resource limits to prevent denial-of-service:

  • MaxRefDepth: Maximum depth for nested $ref resolution (default: 100)
  • MaxCachedDocuments: Maximum external documents to cache (default: 100)
  • MaxFileSize: Maximum file size for external references (default: 10MB)

Configure limits using functional options:

result, err := parser.ParseWithOptions(
	parser.WithFilePath("openapi.yaml"),
	parser.WithMaxRefDepth(50),           // Reduce max depth
	parser.WithMaxCachedDocuments(200),   // Allow more cached docs
	parser.WithMaxFileSize(20*1024*1024), // 20MB limit
)

Source Naming for Pre-Parsed Documents

When parsing from bytes or io.Reader (common when fetching specs from HTTP or databases), the default SourcePath is generic ("ParseBytes.yaml" or "ParseReader.yaml"). Use WithSourceName to set a meaningful identifier:

result, err := parser.ParseWithOptions(
	parser.WithBytes(specData),
	parser.WithSourceName("users-api"),
)

This is especially important when joining multiple pre-parsed documents, as the joiner uses SourcePath in collision reports. Without meaningful names, collision reports show unhelpful text like "ParseBytes.yaml vs ParseBytes.yaml". The joiner will emit info-level warnings for documents with generic source names.

Alternatively, you can set SourcePath directly on the ParseResult after parsing:

result, err := parser.ParseWithOptions(parser.WithBytes(specData))
result.SourcePath = "users-api"

OAS 3.2.0 Features

OAS 3.2.0 introduces several new capabilities:

  • $self: Document identity/base URI (OAS3Document.Self)
  • Query method: New HTTP method (PathItem.Query)
  • additionalOperations: Custom HTTP methods (PathItem.AdditionalOperations)
  • mediaTypes: Reusable media type definitions (Components.MediaTypes)

JSON Schema 2020-12 Keywords

The parser supports JSON Schema Draft 2020-12 keywords for OAS 3.1+:

  • unevaluatedProperties/unevaluatedItems: Strict validation (can be bool, *Schema, or map)
  • contentEncoding/contentMediaType/contentSchema: Encoded content validation
  • prefixItems, contains, propertyNames, dependentSchemas, $defs: Advanced schema features

Array Index References

JSON Pointer references support array indices per RFC 6901:

$ref: '#/paths/~1users/get/parameters/0/schema'

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.

Document Type Helpers

ParseResult provides convenient methods for version checking and type assertion:

result, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))

// Version checking
if result.IsOAS2() {
	fmt.Println("This is a Swagger 2.0 document")
}
if result.IsOAS3() {
	fmt.Println("This is an OAS 3.x document")
}

// Safe type assertion
if doc, ok := result.OAS3Document(); ok {
	fmt.Printf("API: %s v%s\n", doc.Info.Title, doc.Info.Version)
}
if doc, ok := result.OAS2Document(); ok {
	fmt.Printf("Swagger: %s v%s\n", doc.Info.Title, doc.Info.Version)
}

These helpers eliminate the need for manual type switches on the Document field.

Version-Agnostic Access

For code that needs to work uniformly across OAS 2.0 and 3.x documents without version-specific type switches, use the DocumentAccessor interface:

result, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))
if accessor := result.AsAccessor(); accessor != nil {
    // Unified access to paths, schemas, etc.
    for path := range accessor.GetPaths() {
        fmt.Println("Path:", path)
    }
    for name := range accessor.GetSchemas() {
        // Returns Definitions (2.0) or Components.Schemas (3.x)
        fmt.Println("Schema:", name)
    }
    // Get the schema $ref prefix for this version
    fmt.Println("Prefix:", accessor.SchemaRefPrefix())
}

DocumentAccessor provides methods like GetPaths, GetSchemas, GetSecuritySchemes, GetParameters, and GetResponses that automatically map to the correct location for each OAS version.

After parsing, use these packages for additional operations:

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

Example_deepCopy demonstrates using DeepCopy to create independent copies of parsed documents. This is useful when you need to modify a document without affecting the original (e.g., in fixers or converters).

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/parser"
)

func main() {
	result, err := parser.ParseWithOptions(
		parser.WithFilePath("../testdata/petstore-3.0.yaml"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Type assert to get the OAS3 document
	original, ok := result.Document.(*parser.OAS3Document)
	if !ok {
		log.Fatal("expected OAS3 document")
	}

	// Create a deep copy of the document
	docCopy := original.DeepCopy()

	// Modify the copy without affecting the original
	docCopy.Info.Title = "Modified Petstore API"

	fmt.Printf("Original title: %s\n", original.Info.Title)
	fmt.Printf("Copy title: %s\n", docCopy.Info.Title)
}
Output:

Original title: Petstore API
Copy title: Modified Petstore API
Example (DocumentAccessor)

Example_documentAccessor demonstrates using the DocumentAccessor interface for version-agnostic access to OpenAPI documents. This allows writing code that works identically for both OAS 2.0 and OAS 3.x without type switches.

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/parser"
)

func main() {
	result, err := parser.ParseWithOptions(
		parser.WithFilePath("../testdata/petstore-3.0.yaml"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Get version-agnostic accessor
	accessor := result.AsAccessor()
	if accessor == nil {
		log.Fatal("unsupported document type")
	}

	// Works identically for both OAS 2.0 and OAS 3.x
	fmt.Printf("API: %s\n", accessor.GetInfo().Title)
	fmt.Printf("Paths: %d\n", len(accessor.GetPaths()))
	fmt.Printf("Schemas: %d\n", len(accessor.GetSchemas()))
	fmt.Printf("Schema ref prefix: %s\n", accessor.SchemaRefPrefix())
}
Output:

API: Petstore API
Paths: 2
Schemas: 4
Schema ref prefix: #/components/schemas/
Example (DocumentTypeHelpers)

Example_documentTypeHelpers demonstrates using the type assertion helper methods to safely extract version-specific documents and check document versions.

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/parser"
)

func main() {
	// Parse an OAS 3.x document
	result, err := parser.ParseWithOptions(
		parser.WithFilePath("../testdata/petstore-3.0.yaml"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Use IsOAS2/IsOAS3 for version checking without type assertions
	fmt.Printf("Is OAS 2.0: %v\n", result.IsOAS2())
	fmt.Printf("Is OAS 3.x: %v\n", result.IsOAS3())

	// Use OAS3Document for safe type assertion
	if doc, ok := result.OAS3Document(); ok {
		fmt.Printf("API Title: %s\n", doc.Info.Title)
	}
}
Output:

Is OAS 2.0: false
Is OAS 3.x: true
API Title: Petstore API
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))
	}
}
Example (WithSourceName)

Example_withSourceName demonstrates setting a meaningful source name when parsing from bytes or io.Reader. This is important when later joining documents, as the source name appears in collision reports and warnings.

package main

import (
	"fmt"
	"log"

	"github.com/erraggy/oastools/parser"
)

func main() {
	// When parsing from bytes (e.g., fetched from HTTP), the default source name
	// is "ParseBytes.yaml" which isn't helpful for collision reports.
	specData := []byte(`openapi: "3.0.0"
info:
  title: Users API
  version: "1.0"
paths:
  /users:
    get:
      summary: List users
      responses:
        '200':
          description: OK
`)

	// Use WithSourceName to set a meaningful identifier
	result, err := parser.ParseWithOptions(
		parser.WithBytes(specData),
		parser.WithSourceName("users-api"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// The source name is now "users-api" instead of "ParseBytes.yaml"
	fmt.Printf("Source: %s\n", result.SourcePath)
	fmt.Printf("Version: %s\n", result.Version)
}
Output:

Source: users-api
Version: 3.0.0

Index

Examples

Constants

View Source
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)

View Source
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
)

Variables

This section is empty.

Functions

func FormatBytes added in v1.9.2

func FormatBytes(bytes int64) string

FormatBytes formats a byte count into a human-readable string using binary units (KiB, MiB, etc.)

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, plus any additionalOperations

Types

type Callback

type Callback map[string]*PathItem

Callback is a map of expressions to path items (OAS 3.0+)

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+

	// OAS 3.2+ additions
	MediaTypes map[string]*MediaType `yaml:"mediaTypes,omitempty" json:"mediaTypes,omitempty"` // OAS 3.2+

	// 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) DeepCopy added in v1.20.0

func (in *Components) DeepCopy() *Components

DeepCopy creates a deep copy of Components.

func (*Components) DeepCopyInto added in v1.20.0

func (in *Components) DeepCopyInto(out *Components)

DeepCopyInto copies Components into out.

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) DeepCopy added in v1.20.0

func (in *Contact) DeepCopy() *Contact

DeepCopy creates a deep copy of Contact.

func (*Contact) DeepCopyInto added in v1.20.0

func (in *Contact) DeepCopyInto(out *Contact)

DeepCopyInto copies Contact into out.

func (*Contact) MarshalJSON added in v1.6.1

func (c *Contact) MarshalJSON() ([]byte, error)

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

func (c *Contact) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for Contact. This captures unknown fields (specification extensions like x-*) in the Extra map.

type ContextLogger added in v1.21.0

type ContextLogger struct {
	// contains filtered or unexported fields
}

ContextLogger wraps a Logger to include context in all operations. This is useful for passing request-scoped values through the logging pipeline.

func NewContextLogger added in v1.21.0

func NewContextLogger(logger Logger, ctx context.Context) *ContextLogger

NewContextLogger creates a new ContextLogger.

func (*ContextLogger) Context added in v1.21.0

func (c *ContextLogger) Context() context.Context

Context returns the context associated with this logger.

func (*ContextLogger) Debug added in v1.21.0

func (c *ContextLogger) Debug(msg string, attrs ...any)

Debug implements Logger.

func (*ContextLogger) Error added in v1.21.0

func (c *ContextLogger) Error(msg string, attrs ...any)

Error implements Logger.

func (*ContextLogger) Info added in v1.21.0

func (c *ContextLogger) Info(msg string, attrs ...any)

Info implements Logger.

func (*ContextLogger) Warn added in v1.21.0

func (c *ContextLogger) Warn(msg string, attrs ...any)

Warn implements Logger.

func (*ContextLogger) With added in v1.21.0

func (c *ContextLogger) With(attrs ...any) Logger

With implements Logger.

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) DeepCopy added in v1.20.0

func (in *Discriminator) DeepCopy() *Discriminator

DeepCopy creates a deep copy of Discriminator.

func (*Discriminator) DeepCopyInto added in v1.20.0

func (in *Discriminator) DeepCopyInto(out *Discriminator)

DeepCopyInto copies Discriminator into out.

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 DocumentAccessor added in v1.33.1

type DocumentAccessor interface {
	// GetInfo returns the API metadata.
	// Returns nil if Info is not set.
	GetInfo() *Info

	// GetPaths returns the path items map.
	// Returns nil if Paths is not set.
	GetPaths() Paths

	// GetTags returns the tag definitions.
	// Returns nil if Tags is not set.
	GetTags() []*Tag

	// GetSecurity returns the global security requirements.
	// Returns nil if Security is not set.
	GetSecurity() []SecurityRequirement

	// GetExternalDocs returns the external documentation reference.
	// Returns nil if ExternalDocs is not set.
	GetExternalDocs() *ExternalDocs

	// GetSchemas returns the schema definitions.
	// For OAS 2.0: returns doc.Definitions
	// For OAS 3.x: returns doc.Components.Schemas
	// Returns nil if the schema container is not set (OAS2 Definitions nil, or
	// OAS3 Components nil or Components.Schemas nil). An empty map is returned
	// only when the container exists but has no entries.
	GetSchemas() map[string]*Schema

	// GetSecuritySchemes returns the security scheme definitions.
	// For OAS 2.0: returns doc.SecurityDefinitions
	// For OAS 3.x: returns doc.Components.SecuritySchemes
	// Returns nil if no security schemes are defined.
	GetSecuritySchemes() map[string]*SecurityScheme

	// GetParameters returns the reusable parameter definitions.
	// For OAS 2.0: returns doc.Parameters
	// For OAS 3.x: returns doc.Components.Parameters
	// Returns nil if no parameters are defined.
	GetParameters() map[string]*Parameter

	// GetResponses returns the reusable response definitions.
	// For OAS 2.0: returns doc.Responses
	// For OAS 3.x: returns doc.Components.Responses
	// Returns nil if no responses are defined.
	GetResponses() map[string]*Response

	// GetVersion returns the OASVersion enum for this document.
	GetVersion() OASVersion

	// GetVersionString returns the version string (e.g., "2.0", "3.0.3", "3.1.0").
	GetVersionString() string

	// SchemaRefPrefix returns the JSON reference prefix for schemas.
	// For OAS 2.0: returns "#/definitions/"
	// For OAS 3.x: returns "#/components/schemas/"
	SchemaRefPrefix() string
}

DocumentAccessor provides a unified read-only interface for accessing common fields across OAS 2.0 and OAS 3.x documents. This interface abstracts away version-specific differences for fields that have semantic equivalence between versions.

Fields with identical structure across versions

  • Info, Paths, Tags, Security, ExternalDocs

Fields with semantic equivalence (different locations, same meaning)

  • Schemas: OAS 2.0 doc.Definitions vs OAS 3.x doc.Components.Schemas
  • SecuritySchemes: OAS 2.0 doc.SecurityDefinitions vs OAS 3.x doc.Components.SecuritySchemes
  • Parameters: OAS 2.0 doc.Parameters vs OAS 3.x doc.Components.Parameters
  • Responses: OAS 2.0 doc.Responses vs OAS 3.x doc.Components.Responses

Accessing version-specific fields

For version-specific fields (Servers, Webhooks, RequestBodies, etc.), use the version-specific document types directly via ParseResult.OAS2Document or ParseResult.OAS3Document methods on the ParseResult.

Return value semantics

Methods returning maps (GetPaths, GetSchemas, etc.) return nil when the field is not set or when a required parent object is nil (e.g., OAS3 Components). These methods return direct references to the underlying data structures, so callers should avoid modifying the returned values unless they intend to mutate the document. If you need to modify the data, make a copy first.

Example usage

result, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))
if accessor := result.AsAccessor(); accessor != nil {
    // Works for both OAS 2.0 and OAS 3.x
    for path, item := range accessor.GetPaths() {
        fmt.Println("Path:", path)
    }
    for name, schema := range accessor.GetSchemas() {
        fmt.Println("Schema:", name)
    }
}

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) DeepCopy added in v1.20.0

func (in *Encoding) DeepCopy() *Encoding

DeepCopy creates a deep copy of Encoding.

func (*Encoding) DeepCopyInto added in v1.20.0

func (in *Encoding) DeepCopyInto(out *Encoding)

DeepCopyInto copies Encoding into out.

func (*Encoding) MarshalJSON added in v1.6.1

func (e *Encoding) MarshalJSON() ([]byte, error)

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

func (e *Encoding) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *Example) DeepCopy() *Example

DeepCopy creates a deep copy of Example.

func (*Example) DeepCopyInto added in v1.20.0

func (in *Example) DeepCopyInto(out *Example)

DeepCopyInto copies Example into out.

func (*Example) MarshalJSON added in v1.6.1

func (e *Example) MarshalJSON() ([]byte, error)

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

func (e *Example) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *ExternalDocs) DeepCopy() *ExternalDocs

DeepCopy creates a deep copy of ExternalDocs.

func (*ExternalDocs) DeepCopyInto added in v1.20.0

func (in *ExternalDocs) DeepCopyInto(out *ExternalDocs)

DeepCopyInto copies ExternalDocs into out.

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

type HTTPFetcher func(url string) ([]byte, string, error)

HTTPFetcher is a function type for fetching content from HTTP/HTTPS URLs Returns the response body, content-type header, and any error

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) DeepCopy added in v1.20.0

func (in *Header) DeepCopy() *Header

DeepCopy creates a deep copy of Header.

func (*Header) DeepCopyInto added in v1.20.0

func (in *Header) DeepCopyInto(out *Header)

DeepCopyInto copies Header into out.

func (*Header) MarshalJSON added in v1.6.1

func (h *Header) MarshalJSON() ([]byte, error)

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

func (h *Header) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *Info) DeepCopy() *Info

DeepCopy creates a deep copy of Info.

func (*Info) DeepCopyInto added in v1.20.0

func (in *Info) DeepCopyInto(out *Info)

DeepCopyInto copies Info into out.

func (*Info) MarshalJSON added in v1.6.1

func (i *Info) MarshalJSON() ([]byte, error)

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

func (i *Info) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *Items) DeepCopy() *Items

DeepCopy creates a deep copy of Items.

func (*Items) DeepCopyInto added in v1.20.0

func (in *Items) DeepCopyInto(out *Items)

DeepCopyInto copies Items into out.

func (*Items) MarshalJSON added in v1.6.1

func (i *Items) MarshalJSON() ([]byte, error)

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

func (i *Items) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *License) DeepCopy() *License

DeepCopy creates a deep copy of License.

func (*License) DeepCopyInto added in v1.20.0

func (in *License) DeepCopyInto(out *License)

DeepCopyInto copies License into out.

func (*License) MarshalJSON added in v1.6.1

func (l *License) MarshalJSON() ([]byte, error)

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

func (l *License) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for License. This captures unknown fields (specification extensions like x-*) in the Extra map.

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) DeepCopy added in v1.20.0

func (in *Link) DeepCopy() *Link

DeepCopy creates a deep copy of Link.

func (*Link) DeepCopyInto added in v1.20.0

func (in *Link) DeepCopyInto(out *Link)

DeepCopyInto copies Link into out.

func (*Link) MarshalJSON added in v1.6.1

func (l *Link) MarshalJSON() ([]byte, error)

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

func (l *Link) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for Link. This captures unknown fields (specification extensions like x-*) in the Extra map.

type Logger added in v1.21.0

type Logger interface {
	// Debug logs at debug level. Use for detailed diagnostic information.
	Debug(msg string, attrs ...any)

	// Info logs at info level. Use for general operational information.
	Info(msg string, attrs ...any)

	// Warn logs at warn level. Use for potentially harmful situations.
	Warn(msg string, attrs ...any)

	// Error logs at error level. Use for error conditions.
	Error(msg string, attrs ...any)

	// With returns a new Logger with the given attributes prepended to every log.
	// This is useful for adding context that applies to multiple log calls.
	With(attrs ...any) Logger
}

Logger is the interface that oastools uses for structured logging.

The interface is designed to be minimal yet compatible with popular logging libraries including log/slog, zap, and zerolog. It uses variadic key-value pairs for structured attributes, following the same convention as log/slog.

Implementations should treat attrs as alternating key-value pairs:

logger.Debug("resolved reference", "ref", "#/components/schemas/Pet", "depth", 3)

Keys should be strings, and values can be any type that the underlying logger can serialize.

Usage with log/slog

Use NewSlogAdapter to wrap a standard library slog.Logger:

handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
slogger := slog.New(handler)
logger := parser.NewSlogAdapter(slogger)

result, err := parser.ParseWithOptions(
    parser.WithFilePath("api.yaml"),
    parser.WithLogger(logger),
)

Usage with zap

Create a simple adapter implementing the Logger interface:

type ZapAdapter struct {
    logger *zap.SugaredLogger
}

func (z *ZapAdapter) Debug(msg string, attrs ...any) { z.logger.Debugw(msg, attrs...) }
func (z *ZapAdapter) Info(msg string, attrs ...any)  { z.logger.Infow(msg, attrs...) }
func (z *ZapAdapter) Warn(msg string, attrs ...any)  { z.logger.Warnw(msg, attrs...) }
func (z *ZapAdapter) Error(msg string, attrs ...any) { z.logger.Errorw(msg, attrs...) }
func (z *ZapAdapter) With(attrs ...any) parser.Logger {
    return &ZapAdapter{logger: z.logger.With(attrs...)}
}

Usage with zerolog

Create a simple adapter implementing the Logger interface:

type ZerologAdapter struct {
    logger zerolog.Logger
}

func (z *ZerologAdapter) Debug(msg string, attrs ...any) {
    e := z.logger.Debug()
    for i := 0; i < len(attrs)-1; i += 2 {
        e = e.Interface(fmt.Sprint(attrs[i]), attrs[i+1])
    }
    e.Msg(msg)
}
// ... implement other methods similarly

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) DeepCopy added in v1.20.0

func (in *MediaType) DeepCopy() *MediaType

DeepCopy creates a deep copy of MediaType.

func (*MediaType) DeepCopyInto added in v1.20.0

func (in *MediaType) DeepCopyInto(out *MediaType)

DeepCopyInto copies MediaType into out.

func (*MediaType) MarshalJSON added in v1.6.1

func (mt *MediaType) MarshalJSON() ([]byte, error)

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

func (mt *MediaType) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for MediaType. This captures unknown fields (specification extensions like x-*) in the Extra map.

type NopLogger added in v1.21.0

type NopLogger struct{}

NopLogger is a no-op logger that discards all output. It is the default logger used when no logger is configured.

func (NopLogger) Debug added in v1.21.0

func (NopLogger) Debug(_ string, _ ...any)

Debug implements Logger.

func (NopLogger) Error added in v1.21.0

func (NopLogger) Error(_ string, _ ...any)

Error implements Logger.

func (NopLogger) Info added in v1.21.0

func (NopLogger) Info(_ string, _ ...any)

Info implements Logger.

func (NopLogger) Warn added in v1.21.0

func (NopLogger) Warn(_ string, _ ...any)

Warn implements Logger.

func (NopLogger) With added in v1.21.0

func (n NopLogger) With(_ ...any) Logger

With implements Logger.

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) DeepCopy added in v1.20.0

func (in *OAS2Document) DeepCopy() *OAS2Document

DeepCopy creates a deep copy of OAS2Document.

func (*OAS2Document) DeepCopyInto added in v1.20.0

func (in *OAS2Document) DeepCopyInto(out *OAS2Document)

DeepCopyInto copies OAS2Document into out.

func (*OAS2Document) GetExternalDocs added in v1.33.1

func (d *OAS2Document) GetExternalDocs() *ExternalDocs

GetExternalDocs returns the external documentation for OAS 2.0 documents.

func (*OAS2Document) GetInfo added in v1.33.1

func (d *OAS2Document) GetInfo() *Info

GetInfo returns the API metadata for OAS 2.0 documents.

func (*OAS2Document) GetParameters added in v1.33.1

func (d *OAS2Document) GetParameters() map[string]*Parameter

GetParameters returns the reusable parameter definitions for OAS 2.0 documents.

func (*OAS2Document) GetPaths added in v1.33.1

func (d *OAS2Document) GetPaths() Paths

GetPaths returns the path items for OAS 2.0 documents.

func (*OAS2Document) GetResponses added in v1.33.1

func (d *OAS2Document) GetResponses() map[string]*Response

GetResponses returns the reusable response definitions for OAS 2.0 documents.

func (*OAS2Document) GetSchemas added in v1.33.1

func (d *OAS2Document) GetSchemas() map[string]*Schema

GetSchemas returns the schema definitions for OAS 2.0 documents. In OAS 2.0, schemas are stored in doc.Definitions.

func (*OAS2Document) GetSecurity added in v1.33.1

func (d *OAS2Document) GetSecurity() []SecurityRequirement

GetSecurity returns the global security requirements for OAS 2.0 documents.

func (*OAS2Document) GetSecuritySchemes added in v1.33.1

func (d *OAS2Document) GetSecuritySchemes() map[string]*SecurityScheme

GetSecuritySchemes returns the security scheme definitions for OAS 2.0 documents. In OAS 2.0, these are stored in doc.SecurityDefinitions.

func (*OAS2Document) GetTags added in v1.33.1

func (d *OAS2Document) GetTags() []*Tag

GetTags returns the tag definitions for OAS 2.0 documents.

func (*OAS2Document) GetVersion added in v1.33.1

func (d *OAS2Document) GetVersion() OASVersion

GetVersion returns the OASVersion for OAS 2.0 documents.

func (*OAS2Document) GetVersionString added in v1.33.1

func (d *OAS2Document) GetVersionString() string

GetVersionString returns the version string for OAS 2.0 documents.

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) SchemaRefPrefix added in v1.33.1

func (d *OAS2Document) SchemaRefPrefix() string

SchemaRefPrefix returns the JSON reference prefix for OAS 2.0 schemas.

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.

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+

	// OAS 3.2+ additions
	Self string `yaml:"$self,omitempty" json:"$self,omitempty"` // OAS 3.2+ - Document identity/base URI

	// 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) DeepCopy added in v1.20.0

func (in *OAS3Document) DeepCopy() *OAS3Document

DeepCopy creates a deep copy of OAS3Document.

func (*OAS3Document) DeepCopyInto added in v1.20.0

func (in *OAS3Document) DeepCopyInto(out *OAS3Document)

DeepCopyInto copies OAS3Document into out.

func (*OAS3Document) GetExternalDocs added in v1.33.1

func (d *OAS3Document) GetExternalDocs() *ExternalDocs

GetExternalDocs returns the external documentation for OAS 3.x documents.

func (*OAS3Document) GetInfo added in v1.33.1

func (d *OAS3Document) GetInfo() *Info

GetInfo returns the API metadata for OAS 3.x documents.

func (*OAS3Document) GetParameters added in v1.33.1

func (d *OAS3Document) GetParameters() map[string]*Parameter

GetParameters returns the reusable parameter definitions for OAS 3.x documents. In OAS 3.x, these are stored in doc.Components.Parameters.

func (*OAS3Document) GetPaths added in v1.33.1

func (d *OAS3Document) GetPaths() Paths

GetPaths returns the path items for OAS 3.x documents.

func (*OAS3Document) GetResponses added in v1.33.1

func (d *OAS3Document) GetResponses() map[string]*Response

GetResponses returns the reusable response definitions for OAS 3.x documents. In OAS 3.x, these are stored in doc.Components.Responses.

func (*OAS3Document) GetSchemas added in v1.33.1

func (d *OAS3Document) GetSchemas() map[string]*Schema

GetSchemas returns the schema definitions for OAS 3.x documents. In OAS 3.x, schemas are stored in doc.Components.Schemas.

func (*OAS3Document) GetSecurity added in v1.33.1

func (d *OAS3Document) GetSecurity() []SecurityRequirement

GetSecurity returns the global security requirements for OAS 3.x documents.

func (*OAS3Document) GetSecuritySchemes added in v1.33.1

func (d *OAS3Document) GetSecuritySchemes() map[string]*SecurityScheme

GetSecuritySchemes returns the security scheme definitions for OAS 3.x documents. In OAS 3.x, these are stored in doc.Components.SecuritySchemes.

func (*OAS3Document) GetTags added in v1.33.1

func (d *OAS3Document) GetTags() []*Tag

GetTags returns the tag definitions for OAS 3.x documents.

func (*OAS3Document) GetVersion added in v1.33.1

func (d *OAS3Document) GetVersion() OASVersion

GetVersion returns the OASVersion for OAS 3.x documents.

func (*OAS3Document) GetVersionString added in v1.33.1

func (d *OAS3Document) GetVersionString() string

GetVersionString returns the version string for OAS 3.x documents.

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) SchemaRefPrefix added in v1.33.1

func (d *OAS3Document) SchemaRefPrefix() string

SchemaRefPrefix returns the JSON reference prefix for OAS 3.x schemas.

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) DeepCopy added in v1.20.0

func (in *OAuthFlow) DeepCopy() *OAuthFlow

DeepCopy creates a deep copy of OAuthFlow.

func (*OAuthFlow) DeepCopyInto added in v1.20.0

func (in *OAuthFlow) DeepCopyInto(out *OAuthFlow)

DeepCopyInto copies OAuthFlow into out.

func (*OAuthFlow) MarshalJSON added in v1.6.1

func (of *OAuthFlow) MarshalJSON() ([]byte, error)

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

func (of *OAuthFlow) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *OAuthFlows) DeepCopy() *OAuthFlows

DeepCopy creates a deep copy of OAuthFlows.

func (*OAuthFlows) DeepCopyInto added in v1.20.0

func (in *OAuthFlows) DeepCopyInto(out *OAuthFlows)

DeepCopyInto copies OAuthFlows into out.

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) DeepCopy added in v1.20.0

func (in *Operation) DeepCopy() *Operation

DeepCopy creates a deep copy of Operation.

func (*Operation) DeepCopyInto added in v1.20.0

func (in *Operation) DeepCopyInto(out *Operation)

DeepCopyInto copies Operation into out.

func (*Operation) MarshalJSON added in v1.6.1

func (o *Operation) MarshalJSON() ([]byte, error)

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

func (o *Operation) UnmarshalJSON(data []byte) error

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 WithBytes added in v1.11.0

func WithBytes(data []byte) Option

WithBytes specifies a byte slice as the input source

func WithFilePath added in v1.11.0

func WithFilePath(path string) Option

WithFilePath specifies a file path or URL as the input source

func WithInsecureSkipVerify added in v1.18.0

func WithInsecureSkipVerify(enabled bool) Option

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 WithLogger added in v1.21.0

func WithLogger(l Logger) Option

WithLogger sets a structured logger for debug output during parsing. By default, no logging is performed (nil logger).

The logger interface is compatible with log/slog, zap, and zerolog. Use NewSlogAdapter to wrap a *slog.Logger.

Example:

logger := parser.NewSlogAdapter(slog.Default())
result, err := parser.ParseWithOptions(
    parser.WithFilePath("api.yaml"),
    parser.WithLogger(logger),
)

func WithMaxCachedDocuments added in v1.21.0

func WithMaxCachedDocuments(count int) Option

WithMaxCachedDocuments sets the maximum number of external documents to cache during reference resolution. This prevents memory exhaustion from documents with many external references. A value of 0 means use the default (100). Returns an error if count is negative.

func WithMaxFileSize added in v1.21.0

func WithMaxFileSize(size int64) Option

WithMaxFileSize sets the maximum file size in bytes for external reference files. This prevents resource exhaustion from loading arbitrarily large files. A value of 0 means use the default (10MB). Returns an error if size is negative.

func WithMaxRefDepth added in v1.21.0

func WithMaxRefDepth(depth int) Option

WithMaxRefDepth sets the maximum depth for resolving nested $ref pointers. This prevents stack overflow from deeply nested (but non-circular) references. A value of 0 means use the default (100). Returns an error if depth is negative.

func WithReader added in v1.11.0

func WithReader(r io.Reader) Option

WithReader specifies an io.Reader as the input source

func WithResolveHTTPRefs added in v1.18.0

func WithResolveHTTPRefs(enabled bool) Option

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

func WithResolveRefs(enabled bool) Option

WithResolveRefs enables or disables reference resolution ($ref) Default: false

func WithSourceMap added in v1.27.0

func WithSourceMap(enabled bool) Option

WithSourceMap enables or disables source location tracking. When enabled, the ParseResult.SourceMap will contain line/column information for each JSON path in the document. Default: false

func WithSourceName added in v1.40.0

func WithSourceName(name string) Option

WithSourceName specifies a meaningful name for the source document. This is particularly useful when parsing from bytes or reader, where the default names ("ParseBytes.yaml", "ParseReader.yaml") are not descriptive. The name is used in error messages, collision reports when joining, and other diagnostic output.

Example:

result, err := parser.ParseWithOptions(
    parser.WithBytes(data),
    parser.WithSourceName("users-api"),
)

This helps when joining multiple pre-parsed documents:

// Without WithSourceName, collision reports show "ParseBytes.yaml vs ParseBytes.yaml"
// With WithSourceName, collision reports show "users-api vs billing-api"

func WithUserAgent added in v1.11.0

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent string for HTTP requests Default: "oastools/vX.Y.Z"

func WithValidateStructure added in v1.11.0

func WithValidateStructure(enabled bool) Option

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) DeepCopy added in v1.20.0

func (in *Parameter) DeepCopy() *Parameter

DeepCopy creates a deep copy of Parameter.

func (*Parameter) DeepCopyInto added in v1.20.0

func (in *Parameter) DeepCopyInto(out *Parameter)

DeepCopyInto copies Parameter into out.

func (*Parameter) MarshalJSON added in v1.6.1

func (p *Parameter) MarshalJSON() ([]byte, error)

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

func (p *Parameter) UnmarshalJSON(data []byte) error

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
	// SourceMap contains JSON path to source location mappings.
	// Only populated when Parser.BuildSourceMap is true.
	SourceMap *SourceMap
}

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) AsAccessor added in v1.33.1

func (pr *ParseResult) AsAccessor() DocumentAccessor

AsAccessor returns a DocumentAccessor for version-agnostic access to the parsed document. Returns nil if the document type is unknown or nil.

This method provides a convenient way to work with parsed documents without needing to check the version and perform type assertions:

result, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))
if accessor := result.AsAccessor(); accessor != nil {
    schemas := accessor.GetSchemas() // Works for both OAS 2.0 and 3.x
}

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

func (*ParseResult) IsOAS2 added in v1.25.0

func (pr *ParseResult) IsOAS2() bool

IsOAS2 returns true if the parsed document is an OpenAPI 2.0 (Swagger) specification. This is a convenience method for checking the document version without type assertions.

func (*ParseResult) IsOAS3 added in v1.25.0

func (pr *ParseResult) IsOAS3() bool

IsOAS3 returns true if the parsed document is an OpenAPI 3.x specification (including 3.0.x, 3.1.x, and 3.2.x). This is a convenience method for checking the document version without type assertions.

func (*ParseResult) OAS2Document added in v1.25.0

func (pr *ParseResult) OAS2Document() (*OAS2Document, bool)

OAS2Document returns the parsed document as an OAS2Document if the specification is version 2.0 (Swagger), and a boolean indicating whether the type assertion succeeded. This is a convenience method that provides a safe type assertion pattern.

Example:

result, _ := parser.ParseWithOptions(parser.WithFilePath("swagger.yaml"))
if doc, ok := result.OAS2Document(); ok {
    fmt.Println("API Title:", doc.Info.Title)
}

func (*ParseResult) OAS3Document added in v1.25.0

func (pr *ParseResult) OAS3Document() (*OAS3Document, bool)

OAS3Document returns the parsed document as an OAS3Document if the specification is version 3.x, and a boolean indicating whether the type assertion succeeded. This is a convenience method that provides a safe type assertion pattern.

Example:

result, _ := parser.ParseWithOptions(parser.WithFilePath("api.yaml"))
if doc, ok := result.OAS3Document(); ok {
    fmt.Println("API Title:", doc.Info.Title)
}

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
	// Logger is the structured logger for debug output
	// If nil, logging is disabled (default)
	Logger Logger

	// MaxRefDepth is the maximum depth for resolving nested $ref pointers.
	// Default: 100
	MaxRefDepth int
	// MaxCachedDocuments is the maximum number of external documents to cache.
	// Default: 100
	MaxCachedDocuments int
	// MaxFileSize is the maximum file size in bytes for external references.
	// Default: 10MB
	MaxFileSize int64
	// BuildSourceMap enables source location tracking during parsing.
	// When enabled, the ParseResult.SourceMap will contain line/column
	// information for each JSON path in the document.
	// Default: false
	BuildSourceMap bool
}

Parser handles OpenAPI specification parsing

func New

func New() *Parser

New creates a new Parser instance with default settings

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"`
	// OAS 3.2+ additions
	AdditionalOperations map[string]*Operation `yaml:"additionalOperations,omitempty" json:"additionalOperations,omitempty"` // OAS 3.2+
	// 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) DeepCopy added in v1.20.0

func (in *PathItem) DeepCopy() *PathItem

DeepCopy creates a deep copy of PathItem.

func (*PathItem) DeepCopyInto added in v1.20.0

func (in *PathItem) DeepCopyInto(out *PathItem)

DeepCopyInto copies PathItem into out.

func (*PathItem) MarshalJSON added in v1.6.1

func (p *PathItem) MarshalJSON() ([]byte, error)

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

func (p *PathItem) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for PathItem. This captures unknown fields (specification extensions like x-*) in the Extra map.

type Paths

type Paths map[string]*PathItem

Paths holds the relative paths to the individual endpoints

type RefLocation added in v1.27.0

type RefLocation struct {
	// Origin is where the $ref is written in the source
	Origin SourceLocation
	// Target is where the referenced content is defined
	Target SourceLocation
	// TargetRef is the $ref string value (e.g., "#/components/schemas/Pet")
	TargetRef string
}

RefLocation tracks both where a $ref is defined and where it points. This enables precise error reporting for reference-related issues.

type RefResolver

type RefResolver struct {

	// SourceMap is the accumulated source map being built during resolution
	// When non-nil, external file source maps are built and merged
	SourceMap *SourceMap
	// ExternalSourceMaps caches source maps for external documents
	ExternalSourceMaps map[string]*SourceMap
	// 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) HasCircularRefs added in v1.20.2

func (r *RefResolver) HasCircularRefs() bool

HasCircularRefs returns true if circular references were detected during resolution. When true, the resolved data contains actual Go circular references and cannot be safely serialized with yaml.Marshal (which would cause an infinite loop).

func (*RefResolver) Resolve

func (r *RefResolver) Resolve(doc map[string]any, ref string) (any, error)

Resolve resolves a $ref reference (local, file, or HTTP)

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

func (r *RefResolver) ResolveLocal(doc map[string]any, ref string) (any, error)

ResolveLocal resolves local references within a document Local refs are in the format: #/path/to/component

func (*RefResolver) SetCacheTTL added in v1.33.2

func (r *RefResolver) SetCacheTTL(ttl time.Duration)

SetCacheTTL sets the time-to-live for cached HTTP documents. A positive duration enables TTL-based cache expiration. Zero (default) caches forever for backward compatibility. A negative duration disables caching entirely.

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) DeepCopy added in v1.20.0

func (in *Reference) DeepCopy() *Reference

DeepCopy creates a deep copy of Reference.

func (*Reference) DeepCopyInto added in v1.20.0

func (in *Reference) DeepCopyInto(out *Reference)

DeepCopyInto copies Reference into out.

func (*Reference) MarshalJSON added in v1.6.1

func (r *Reference) MarshalJSON() ([]byte, error)

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

func (r *Reference) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *RequestBody) DeepCopy() *RequestBody

DeepCopy creates a deep copy of RequestBody.

func (*RequestBody) DeepCopyInto added in v1.20.0

func (in *RequestBody) DeepCopyInto(out *RequestBody)

DeepCopyInto copies RequestBody into out.

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) DeepCopy added in v1.20.0

func (in *Response) DeepCopy() *Response

DeepCopy creates a deep copy of Response.

func (*Response) DeepCopyInto added in v1.20.0

func (in *Response) DeepCopyInto(out *Response)

DeepCopyInto copies Response into out.

func (*Response) MarshalJSON added in v1.6.1

func (r *Response) MarshalJSON() ([]byte, error)

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

func (r *Response) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *Responses) DeepCopy() *Responses

DeepCopy creates a deep copy of Responses.

func (*Responses) DeepCopyInto added in v1.20.0

func (in *Responses) DeepCopyInto(out *Responses)

DeepCopyInto copies Responses into out.

func (*Responses) MarshalJSON added in v1.6.1

func (r *Responses) MarshalJSON() ([]byte, error)

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

func (r *Responses) UnmarshalJSON(data []byte) error

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

func (r *Responses) UnmarshalYAML(unmarshal func(any) error) error

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
	UnevaluatedItems any       `yaml:"unevaluatedItems,omitempty" json:"unevaluatedItems,omitempty"` // JSON Schema Draft 2020-12: *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
	UnevaluatedProperties any                 `yaml:"unevaluatedProperties,omitempty" json:"unevaluatedProperties,omitempty"` // JSON Schema Draft 2020-12: *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.

	// Content keywords (JSON Schema Draft 2020-12)
	ContentEncoding  string  `yaml:"contentEncoding,omitempty" json:"contentEncoding,omitempty"`   // e.g., "base64", "base32"
	ContentMediaType string  `yaml:"contentMediaType,omitempty" json:"contentMediaType,omitempty"` // e.g., "application/json"
	ContentSchema    *Schema `yaml:"contentSchema,omitempty" json:"contentSchema,omitempty"`       // Schema for decoded content

	// 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) DeepCopy added in v1.20.0

func (in *Schema) DeepCopy() *Schema

DeepCopy creates a deep copy of Schema.

func (*Schema) DeepCopyInto added in v1.20.0

func (in *Schema) DeepCopyInto(out *Schema)

DeepCopyInto copies Schema into out.

func (*Schema) MarshalJSON added in v1.6.1

func (s *Schema) MarshalJSON() ([]byte, error)

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

func (s *Schema) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for Schema. This captures unknown fields (specification extensions like x-*) in the Extra map.

type SecurityRequirement

type SecurityRequirement map[string][]string

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) DeepCopy added in v1.20.0

func (in *SecurityScheme) DeepCopy() *SecurityScheme

DeepCopy creates a deep copy of SecurityScheme.

func (*SecurityScheme) DeepCopyInto added in v1.20.0

func (in *SecurityScheme) DeepCopyInto(out *SecurityScheme)

DeepCopyInto copies SecurityScheme into out.

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) DeepCopy added in v1.20.0

func (in *Server) DeepCopy() *Server

DeepCopy creates a deep copy of Server.

func (*Server) DeepCopyInto added in v1.20.0

func (in *Server) DeepCopyInto(out *Server)

DeepCopyInto copies Server into out.

func (*Server) MarshalJSON added in v1.6.1

func (s *Server) MarshalJSON() ([]byte, error)

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

func (s *Server) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *ServerVariable) DeepCopy() *ServerVariable

DeepCopy creates a deep copy of ServerVariable.

func (*ServerVariable) DeepCopyInto added in v1.20.0

func (in *ServerVariable) DeepCopyInto(out *ServerVariable)

DeepCopyInto copies ServerVariable into out.

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 SlogAdapter added in v1.21.0

type SlogAdapter struct {
	// contains filtered or unexported fields
}

SlogAdapter wraps a *slog.Logger to implement the Logger interface. This allows using the standard library's slog package with oastools.

func NewSlogAdapter added in v1.21.0

func NewSlogAdapter(logger *slog.Logger) *SlogAdapter

NewSlogAdapter creates a new SlogAdapter from a *slog.Logger. If logger is nil, slog.Default() is used.

func (*SlogAdapter) Debug added in v1.21.0

func (s *SlogAdapter) Debug(msg string, attrs ...any)

Debug implements Logger.

func (*SlogAdapter) Error added in v1.21.0

func (s *SlogAdapter) Error(msg string, attrs ...any)

Error implements Logger.

func (*SlogAdapter) Info added in v1.21.0

func (s *SlogAdapter) Info(msg string, attrs ...any)

Info implements Logger.

func (*SlogAdapter) Warn added in v1.21.0

func (s *SlogAdapter) Warn(msg string, attrs ...any)

Warn implements Logger.

func (*SlogAdapter) With added in v1.21.0

func (s *SlogAdapter) With(attrs ...any) Logger

With implements Logger.

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 SourceLocation added in v1.27.0

type SourceLocation struct {
	// Line is the 1-based line number (0 if unknown)
	Line int
	// Column is the 1-based column number (0 if unknown)
	Column int
	// File is the source file path (empty for the main document)
	File string
}

SourceLocation represents a position in a source document. Line and Column are 1-based (matching editor conventions). A zero Line value indicates the location is unknown.

func (SourceLocation) IsKnown added in v1.27.0

func (s SourceLocation) IsKnown() bool

IsKnown returns true if this location has valid line information.

func (SourceLocation) String added in v1.27.0

func (s SourceLocation) String() string

String returns a human-readable location string. Format: "file:line:column" or "line:column" if no file, or "<unknown>" if not known.

type SourceMap added in v1.27.0

type SourceMap struct {
	// contains filtered or unexported fields
}

SourceMap provides JSON path to source location mapping. It enables looking up the original source position for any element in a parsed OpenAPI document.

The SourceMap is built during parsing when WithSourceMap(true) is used. It uses JSON path notation for keys (e.g., "$.paths./users.get.responses.200").

func NewSourceMap added in v1.27.0

func NewSourceMap() *SourceMap

NewSourceMap creates an empty SourceMap.

func (*SourceMap) Copy added in v1.27.0

func (sm *SourceMap) Copy() *SourceMap

Copy creates a deep copy of the SourceMap. Returns nil if the receiver is nil.

func (*SourceMap) Get added in v1.27.0

func (sm *SourceMap) Get(path string) SourceLocation

Get returns the source location for a JSON path. Returns a zero SourceLocation if the path is not found.

func (*SourceMap) GetKey added in v1.27.0

func (sm *SourceMap) GetKey(path string) SourceLocation

GetKey returns the source location of a map key at the given path. This is useful for errors about the key itself (e.g., "unknown field"). Returns a zero SourceLocation if the path is not found.

func (*SourceMap) GetRef added in v1.27.0

func (sm *SourceMap) GetRef(path string) RefLocation

GetRef returns the reference location information for a path containing a $ref. Returns a zero RefLocation if no $ref exists at the path.

func (*SourceMap) Has added in v1.27.0

func (sm *SourceMap) Has(path string) bool

Has returns true if the path exists in the source map.

func (*SourceMap) Len added in v1.27.0

func (sm *SourceMap) Len() int

Len returns the number of paths in the source map.

func (*SourceMap) Merge added in v1.27.0

func (sm *SourceMap) Merge(other *SourceMap)

Merge combines another SourceMap into this one. Locations from the other map overwrite existing locations with the same path. Does nothing if either receiver or other is nil.

func (*SourceMap) Paths added in v1.27.0

func (sm *SourceMap) Paths() []string

Paths returns all JSON paths in the source map, sorted alphabetically. Returns nil if the receiver is nil.

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) DeepCopy added in v1.20.0

func (in *Tag) DeepCopy() *Tag

DeepCopy creates a deep copy of Tag.

func (*Tag) DeepCopyInto added in v1.20.0

func (in *Tag) DeepCopyInto(out *Tag)

DeepCopyInto copies Tag into out.

func (*Tag) MarshalJSON added in v1.6.1

func (t *Tag) MarshalJSON() ([]byte, error)

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

func (t *Tag) UnmarshalJSON(data []byte) error

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) DeepCopy added in v1.20.0

func (in *XML) DeepCopy() *XML

DeepCopy creates a deep copy of XML.

func (*XML) DeepCopyInto added in v1.20.0

func (in *XML) DeepCopyInto(out *XML)

DeepCopyInto copies XML into out.

func (*XML) MarshalJSON added in v1.6.1

func (x *XML) MarshalJSON() ([]byte, error)

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

func (x *XML) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for XML. This captures unknown fields (specification extensions like x-*) in the Extra map.

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.

Jump to

Keyboard shortcuts

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