parser

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2025 License: MIT Imports: 9 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.

Quick Start

Parse a file:

result, err := parser.Parse("openapi.yaml", false, true)
if err != nil {
	log.Fatal(err)
}
if len(result.Errors) > 0 {
	fmt.Printf("Parse errors: %d\n", len(result.Errors))
}

Or create a reusable Parser instance:

p := parser.New()
p.ResolveRefs = false
result1, _ := p.Parse("api1.yaml")
result2, _ := p.Parse("api2.yaml")

Features and Security

The parser validates operation IDs, status codes, and HTTP status codes. For external references, it prevents path traversal attacks by restricting file access to the base directory and subdirectories. Reference resolution caches up to 1000 documents to prevent memory exhaustion. See the examples in example_test.go for more details.

ParseResult Fields

ParseResult includes the detected Version, OASVersion, SourceFormat (JSON or YAML), and any parsing Errors or Warnings. The Document field contains the parsed OAS2Document or OAS3Document. The SourceFormat field can be used by conversion and joining tools to preserve the original file format. See the exported ParseResult and document type fields for complete details.

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

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
)
View Source
const (
	// ResponseDefault represents the default response (for any status code not explicitly defined)
	ResponseDefault = "default"
)

Response code constants

Variables

This section is empty.

Functions

func GetOAS2Operations added in v1.6.0

func GetOAS2Operations(pathItem *PathItem) map[string]*Operation

GetOAS2Operations extracts a map of all operations from a PathItem. Returns a map with keys for HTTP methods (get, put, post, delete, options, head, patch) and values pointing to the corresponding Operation (or nil if not defined). This is used for OAS 2.0 paths that do not support the TRACE method.

func GetOAS3Operations added in v1.6.0

func GetOAS3Operations(pathItem *PathItem) map[string]*Operation

GetOAS3Operations extracts a map of all operations from a PathItem. Returns a map with keys for HTTP methods (get, put, post, delete, options, head, patch, trace) and values pointing to the corresponding Operation (or nil if not defined). This is used for OAS 3.x paths that support the TRACE method.

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"`
	Responses       map[string]*Response       `yaml:"responses,omitempty"`
	Parameters      map[string]*Parameter      `yaml:"parameters,omitempty"`
	Examples        map[string]*Example        `yaml:"examples,omitempty"`
	RequestBodies   map[string]*RequestBody    `yaml:"requestBodies,omitempty"`
	Headers         map[string]*Header         `yaml:"headers,omitempty"`
	SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty"`
	Links           map[string]*Link           `yaml:"links,omitempty"`
	Callbacks       map[string]*Callback       `yaml:"callbacks,omitempty"`

	// OAS 3.1+ additions
	PathItems map[string]*PathItem `yaml:"pathItems,omitempty"` // OAS 3.1+

	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Components holds reusable objects for different aspects of the OAS (OAS 3.0+)

type Contact

type Contact struct {
	Name  string `yaml:"name,omitempty"`
	URL   string `yaml:"url,omitempty"`
	Email string `yaml:"email,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Contact information for the exposed API

type Discriminator

type Discriminator struct {
	PropertyName string                 `yaml:"propertyName"`
	Mapping      map[string]string      `yaml:"mapping,omitempty"`
	Extra        map[string]interface{} `yaml:",inline"`
}

Discriminator represents a discriminator for polymorphism (OAS 3.0+)

type Encoding

type Encoding struct {
	ContentType   string             `yaml:"contentType,omitempty"`
	Headers       map[string]*Header `yaml:"headers,omitempty"`
	Style         string             `yaml:"style,omitempty"`
	Explode       *bool              `yaml:"explode,omitempty"`
	AllowReserved bool               `yaml:"allowReserved,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Encoding defines encoding for a specific property (OAS 3.0+)

type Example

type Example struct {
	Ref           string      `yaml:"$ref,omitempty"`
	Summary       string      `yaml:"summary,omitempty"`
	Description   string      `yaml:"description,omitempty"`
	Value         interface{} `yaml:"value,omitempty"`
	ExternalValue string      `yaml:"externalValue,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Example represents an example object (OAS 3.0+)

type ExternalDocs

type ExternalDocs struct {
	Description string `yaml:"description,omitempty"`
	URL         string `yaml:"url"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

ExternalDocs allows referencing external documentation

type Header struct {
	Ref         string `yaml:"$ref,omitempty"`
	Description string `yaml:"description,omitempty"`
	Required    bool   `yaml:"required,omitempty"`
	Deprecated  bool   `yaml:"deprecated,omitempty"` // OAS 3.0+

	// OAS 3.0+ fields
	Style    string                `yaml:"style,omitempty"`
	Explode  *bool                 `yaml:"explode,omitempty"`
	Schema   *Schema               `yaml:"schema,omitempty"`
	Example  interface{}           `yaml:"example,omitempty"`
	Examples map[string]*Example   `yaml:"examples,omitempty"`
	Content  map[string]*MediaType `yaml:"content,omitempty"`

	// OAS 2.0 fields
	Type             string        `yaml:"type,omitempty"`             // OAS 2.0
	Format           string        `yaml:"format,omitempty"`           // OAS 2.0
	Items            *Items        `yaml:"items,omitempty"`            // OAS 2.0
	CollectionFormat string        `yaml:"collectionFormat,omitempty"` // OAS 2.0
	Default          interface{}   `yaml:"default,omitempty"`          // OAS 2.0
	Maximum          *float64      `yaml:"maximum,omitempty"`          // OAS 2.0
	ExclusiveMaximum bool          `yaml:"exclusiveMaximum,omitempty"` // OAS 2.0
	Minimum          *float64      `yaml:"minimum,omitempty"`          // OAS 2.0
	ExclusiveMinimum bool          `yaml:"exclusiveMinimum,omitempty"` // OAS 2.0
	MaxLength        *int          `yaml:"maxLength,omitempty"`        // OAS 2.0
	MinLength        *int          `yaml:"minLength,omitempty"`        // OAS 2.0
	Pattern          string        `yaml:"pattern,omitempty"`          // OAS 2.0
	MaxItems         *int          `yaml:"maxItems,omitempty"`         // OAS 2.0
	MinItems         *int          `yaml:"minItems,omitempty"`         // OAS 2.0
	UniqueItems      bool          `yaml:"uniqueItems,omitempty"`      // OAS 2.0
	Enum             []interface{} `yaml:"enum,omitempty"`             // OAS 2.0
	MultipleOf       *float64      `yaml:"multipleOf,omitempty"`       // OAS 2.0

	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Header represents a header object

type Info

type Info struct {
	Title          string   `yaml:"title"`
	Description    string   `yaml:"description,omitempty"`
	TermsOfService string   `yaml:"termsOfService,omitempty"`
	Contact        *Contact `yaml:"contact,omitempty"`
	License        *License `yaml:"license,omitempty"`
	Version        string   `yaml:"version"`
	// OAS 3.1+ additions
	Summary string `yaml:"summary,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	// and any other fields not explicitly defined in the struct
	Extra map[string]interface{} `yaml:",inline"`
}

Info provides metadata about the API Common across all OAS versions (2.0, 3.0, 3.1, 3.2)

type Items

type Items struct {
	Type             string                 `yaml:"type"`
	Format           string                 `yaml:"format,omitempty"`
	Items            *Items                 `yaml:"items,omitempty"`
	CollectionFormat string                 `yaml:"collectionFormat,omitempty"`
	Default          interface{}            `yaml:"default,omitempty"`
	Maximum          *float64               `yaml:"maximum,omitempty"`
	ExclusiveMaximum bool                   `yaml:"exclusiveMaximum,omitempty"`
	Minimum          *float64               `yaml:"minimum,omitempty"`
	ExclusiveMinimum bool                   `yaml:"exclusiveMinimum,omitempty"`
	MaxLength        *int                   `yaml:"maxLength,omitempty"`
	MinLength        *int                   `yaml:"minLength,omitempty"`
	Pattern          string                 `yaml:"pattern,omitempty"`
	MaxItems         *int                   `yaml:"maxItems,omitempty"`
	MinItems         *int                   `yaml:"minItems,omitempty"`
	UniqueItems      bool                   `yaml:"uniqueItems,omitempty"`
	Enum             []interface{}          `yaml:"enum,omitempty"`
	MultipleOf       *float64               `yaml:"multipleOf,omitempty"`
	Extra            map[string]interface{} `yaml:",inline"`
}

Items represents items object for array parameters (OAS 2.0)

type License

type License struct {
	Name       string `yaml:"name"`
	URL        string `yaml:"url,omitempty"`
	Identifier string `yaml:"identifier,omitempty"` // OAS 3.1+
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

License information for the exposed API

type Link struct {
	Ref          string                 `yaml:"$ref,omitempty"`
	OperationRef string                 `yaml:"operationRef,omitempty"`
	OperationID  string                 `yaml:"operationId,omitempty"`
	Parameters   map[string]interface{} `yaml:"parameters,omitempty"`
	RequestBody  interface{}            `yaml:"requestBody,omitempty"`
	Description  string                 `yaml:"description,omitempty"`
	Server       *Server                `yaml:"server,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Link represents a possible design-time link for a response (OAS 3.0+)

type MediaType

type MediaType struct {
	Schema   *Schema              `yaml:"schema,omitempty"`
	Example  interface{}          `yaml:"example,omitempty"`
	Examples map[string]*Example  `yaml:"examples,omitempty"`
	Encoding map[string]*Encoding `yaml:"encoding,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

MediaType provides schema and examples for the media type (OAS 3.0+)

type OAS2Document

type OAS2Document struct {
	Swagger             string                     `yaml:"swagger"` // Required: "2.0"
	Info                *Info                      `yaml:"info"`    // Required
	Host                string                     `yaml:"host,omitempty"`
	BasePath            string                     `yaml:"basePath,omitempty"`
	Schemes             []string                   `yaml:"schemes,omitempty"` // e.g., ["http", "https"]
	Consumes            []string                   `yaml:"consumes,omitempty"`
	Produces            []string                   `yaml:"produces,omitempty"`
	Paths               Paths                      `yaml:"paths"` // Required
	Definitions         map[string]*Schema         `yaml:"definitions,omitempty"`
	Parameters          map[string]*Parameter      `yaml:"parameters,omitempty"`
	Responses           map[string]*Response       `yaml:"responses,omitempty"`
	SecurityDefinitions map[string]*SecurityScheme `yaml:"securityDefinitions,omitempty"`
	Security            []SecurityRequirement      `yaml:"security,omitempty"`
	Tags                []*Tag                     `yaml:"tags,omitempty"`
	ExternalDocs        *ExternalDocs              `yaml:"externalDocs,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra      map[string]interface{} `yaml:",inline"`
	OASVersion OASVersion             `yaml:"-"`
}

OAS2Document represents an OpenAPI Specification 2.0 (Swagger) document Reference: https://spec.openapis.org/oas/v2.0.html

type OAS3Document

type OAS3Document struct {
	OpenAPI      string                `yaml:"openapi"` // Required: "3.0.x", "3.1.x", or "3.2.x"
	Info         *Info                 `yaml:"info"`    // Required
	Servers      []*Server             `yaml:"servers,omitempty"`
	Paths        Paths                 `yaml:"paths,omitempty"`    // Required in 3.0, optional in 3.1+
	Webhooks     map[string]*PathItem  `yaml:"webhooks,omitempty"` // OAS 3.1+
	Components   *Components           `yaml:"components,omitempty"`
	Security     []SecurityRequirement `yaml:"security,omitempty"`
	Tags         []*Tag                `yaml:"tags,omitempty"`
	ExternalDocs *ExternalDocs         `yaml:"externalDocs,omitempty"`
	OASVersion   OASVersion            `yaml:"-"`

	// OAS 3.1+ additions
	JSONSchemaDialect string `yaml:"jsonSchemaDialect,omitempty"` // OAS 3.1+

	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

OAS3Document represents an OpenAPI Specification 3.x document Supports OAS 3.0.x, 3.1.x, and 3.2.x References: - OAS 3.0.0: https://spec.openapis.org/oas/v3.0.0.html - OAS 3.1.0: https://spec.openapis.org/oas/v3.1.0.html - OAS 3.2.0: https://spec.openapis.org/oas/v3.2.0.html

type OASVersion

type OASVersion int

OASVersion represents each canonical version of the OpenAPI Specification that may be found at: https://github.com/OAI/OpenAPI-Specification/releases

const (
	// Unknown represents an unknown or invalid OAS version
	Unknown OASVersion = iota
	// OASVersion20 OpenAPI Specification Version 2.0 (Swagger)
	OASVersion20
	// OASVersion300 OpenAPI Specification Version 3.0.0
	OASVersion300
	// OASVersion301  OpenAPI Specification Version 3.0.1
	OASVersion301
	// OASVersion302  OpenAPI Specification Version 3.0.2
	OASVersion302
	// OASVersion303  OpenAPI Specification Version 3.0.3
	OASVersion303
	// OASVersion304  OpenAPI Specification Version 3.0.4
	OASVersion304
	// OASVersion310  OpenAPI Specification Version 3.1.0
	OASVersion310
	// OASVersion311  OpenAPI Specification Version 3.1.1
	OASVersion311
	// OASVersion312  OpenAPI Specification Version 3.1.2
	OASVersion312
	// OASVersion320  OpenAPI Specification Version 3.2.0
	OASVersion320
)

func ParseVersion

func ParseVersion(s string) (OASVersion, bool)

ParseVersion will attempt to parse the string s into an OASVersion, and returns false if not valid. This function supports: 1. Exact version matches (e.g., "2.0", "3.0.3") 2. Future patch versions in known major.minor series (e.g., "3.0.5" maps to "3.0.4") 3. Pre-release versions (e.g., "3.0.0-rc0") map to closest match without exceeding base version

For example: - "3.0.5" (not yet released) maps to OASVersion304 (3.0.4) - latest in 3.0.x series - "3.0.0-rc0" maps to OASVersion300 (3.0.0) - the base version - "3.0.5-rc1" maps to OASVersion304 (3.0.4) - closest without exceeding 3.0.5

func (OASVersion) IsValid

func (v OASVersion) IsValid() bool

IsValid returns true if this is a valid version

func (OASVersion) String

func (v OASVersion) String() string

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string                 `yaml:"authorizationUrl,omitempty"`
	TokenURL         string                 `yaml:"tokenUrl,omitempty"`
	RefreshURL       string                 `yaml:"refreshUrl,omitempty"`
	Scopes           map[string]string      `yaml:"scopes"`
	Extra            map[string]interface{} `yaml:",inline"`
}

OAuthFlow represents configuration for a single OAuth flow (OAS 3.0+)

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow             `yaml:"implicit,omitempty"`
	Password          *OAuthFlow             `yaml:"password,omitempty"`
	ClientCredentials *OAuthFlow             `yaml:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow             `yaml:"authorizationCode,omitempty"`
	Extra             map[string]interface{} `yaml:",inline"`
}

OAuthFlows allows configuration of the supported OAuth Flows (OAS 3.0+)

type Operation

type Operation struct {
	Tags         []string              `yaml:"tags,omitempty"`
	Summary      string                `yaml:"summary,omitempty"`
	Description  string                `yaml:"description,omitempty"`
	ExternalDocs *ExternalDocs         `yaml:"externalDocs,omitempty"`
	OperationID  string                `yaml:"operationId,omitempty"`
	Parameters   []*Parameter          `yaml:"parameters,omitempty"`
	RequestBody  *RequestBody          `yaml:"requestBody,omitempty"` // OAS 3.0+
	Responses    *Responses            `yaml:"responses"`
	Callbacks    map[string]*Callback  `yaml:"callbacks,omitempty"` // OAS 3.0+
	Deprecated   bool                  `yaml:"deprecated,omitempty"`
	Security     []SecurityRequirement `yaml:"security,omitempty"`
	Servers      []*Server             `yaml:"servers,omitempty"` // OAS 3.0+
	// OAS 2.0 specific
	Consumes []string `yaml:"consumes,omitempty"` // OAS 2.0
	Produces []string `yaml:"produces,omitempty"` // OAS 2.0
	Schemes  []string `yaml:"schemes,omitempty"`  // OAS 2.0
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Operation describes a single API operation on a path

type Parameter

type Parameter struct {
	Ref         string `yaml:"$ref,omitempty"`
	Name        string `yaml:"name"`
	In          string `yaml:"in"` // "query", "header", "path", "cookie" (OAS 3.0+), "formData", "body" (OAS 2.0)
	Description string `yaml:"description,omitempty"`
	Required    bool   `yaml:"required,omitempty"`
	Deprecated  bool   `yaml:"deprecated,omitempty"` // OAS 3.0+

	// OAS 3.0+ fields
	Style         string                `yaml:"style,omitempty"`
	Explode       *bool                 `yaml:"explode,omitempty"`
	AllowReserved bool                  `yaml:"allowReserved,omitempty"`
	Schema        *Schema               `yaml:"schema,omitempty"`
	Example       interface{}           `yaml:"example,omitempty"`
	Examples      map[string]*Example   `yaml:"examples,omitempty"`
	Content       map[string]*MediaType `yaml:"content,omitempty"`

	// OAS 2.0 fields
	Type             string        `yaml:"type,omitempty"`             // OAS 2.0
	Format           string        `yaml:"format,omitempty"`           // OAS 2.0
	AllowEmptyValue  bool          `yaml:"allowEmptyValue,omitempty"`  // OAS 2.0
	Items            *Items        `yaml:"items,omitempty"`            // OAS 2.0
	CollectionFormat string        `yaml:"collectionFormat,omitempty"` // OAS 2.0
	Default          interface{}   `yaml:"default,omitempty"`          // OAS 2.0
	Maximum          *float64      `yaml:"maximum,omitempty"`          // OAS 2.0
	ExclusiveMaximum bool          `yaml:"exclusiveMaximum,omitempty"` // OAS 2.0
	Minimum          *float64      `yaml:"minimum,omitempty"`          // OAS 2.0
	ExclusiveMinimum bool          `yaml:"exclusiveMinimum,omitempty"` // OAS 2.0
	MaxLength        *int          `yaml:"maxLength,omitempty"`        // OAS 2.0
	MinLength        *int          `yaml:"minLength,omitempty"`        // OAS 2.0
	Pattern          string        `yaml:"pattern,omitempty"`          // OAS 2.0
	MaxItems         *int          `yaml:"maxItems,omitempty"`         // OAS 2.0
	MinItems         *int          `yaml:"minItems,omitempty"`         // OAS 2.0
	UniqueItems      bool          `yaml:"uniqueItems,omitempty"`      // OAS 2.0
	Enum             []interface{} `yaml:"enum,omitempty"`             // OAS 2.0
	MultipleOf       *float64      `yaml:"multipleOf,omitempty"`       // OAS 2.0

	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Parameter describes a single operation parameter

type ParseResult

type ParseResult struct {
	// 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]interface{}
	// Document contains the version-specific parsed document:
	// - *OAS2Document for OpenAPI 2.0
	// - *OAS3Document for OpenAPI 3.x
	Document interface{}
	// Errors contains any parsing or validation errors encountered
	Errors []error
	// Warnings contains non-fatal issues such as ref resolution failures
	Warnings []string
	// OASVersion is the enumerated version of the OpenAPI specification
	OASVersion OASVersion
}

ParseResult contains the parsed OpenAPI specification and metadata. This structure provides both the raw parsed data and version-specific typed representations of the OpenAPI document, and should be treated as immutable.

func Parse added in v1.4.0

func Parse(specPath string, resolveRefs, validateStructure bool) (*ParseResult, error)

Parse is a convenience function that parses an OpenAPI specification file with the specified options. It's equivalent to creating a Parser with New(), setting the options, and calling Parse().

For one-off parsing operations, this function provides a simpler API. For parsing multiple files with the same configuration, create a Parser instance and reuse it.

Example:

result, err := parser.Parse("openapi.yaml", false, true)
if err != nil {
    log.Fatal(err)
}

func ParseBytes added in v1.4.0

func ParseBytes(data []byte, resolveRefs, validateStructure bool) (*ParseResult, error)

ParseBytes is a convenience function that parses an OpenAPI specification from a byte slice with the specified options.

Example:

data := []byte(`openapi: "3.0.0"...`)
result, err := parser.ParseBytes(data, false, true)

func ParseReader added in v1.4.0

func ParseReader(r io.Reader, resolveRefs, validateStructure bool) (*ParseResult, error)

ParseReader is a convenience function that parses an OpenAPI specification from an io.Reader with the specified options.

Example:

file, _ := os.Open("openapi.yaml")
defer file.Close()
result, err := parser.ParseReader(file, false, true)

type Parser

type Parser struct {
	// ResolveRefs determines whether to resolve $ref references
	ResolveRefs bool
	// ValidateStructure determines whether to perform basic structure validation
	ValidateStructure bool
}

Parser handles OpenAPI specification parsing

func 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

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"`
	Summary     string       `yaml:"summary,omitempty"`     // OAS 3.0+
	Description string       `yaml:"description,omitempty"` // OAS 3.0+
	Get         *Operation   `yaml:"get,omitempty"`
	Put         *Operation   `yaml:"put,omitempty"`
	Post        *Operation   `yaml:"post,omitempty"`
	Delete      *Operation   `yaml:"delete,omitempty"`
	Options     *Operation   `yaml:"options,omitempty"`
	Head        *Operation   `yaml:"head,omitempty"`
	Patch       *Operation   `yaml:"patch,omitempty"`
	Trace       *Operation   `yaml:"trace,omitempty"`   // OAS 3.0+
	Servers     []*Server    `yaml:"servers,omitempty"` // OAS 3.0+
	Parameters  []*Parameter `yaml:"parameters,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

PathItem describes the operations available on a single path

type Paths

type Paths map[string]*PathItem

Paths holds the relative paths to the individual endpoints

type RefResolver

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

RefResolver handles $ref resolution in OpenAPI documents

func NewRefResolver

func NewRefResolver(baseDir string) *RefResolver

NewRefResolver creates a new reference resolver

func (*RefResolver) Resolve

func (r *RefResolver) Resolve(doc map[string]interface{}, ref string) (interface{}, error)

Resolve resolves a $ref reference (local or external)

func (*RefResolver) ResolveAllRefs

func (r *RefResolver) ResolveAllRefs(doc map[string]interface{}) error

ResolveAllRefs walks through the entire document and resolves all $ref references

func (*RefResolver) ResolveExternal

func (r *RefResolver) ResolveExternal(ref string) (interface{}, error)

ResolveExternal resolves external file references External refs are in the format: ./file.yaml#/path/to/component or file.yaml#/path/to/component

func (*RefResolver) ResolveLocal

func (r *RefResolver) ResolveLocal(doc map[string]interface{}, ref string) (interface{}, error)

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

type Reference

type Reference struct {
	Ref         string `yaml:"$ref"`
	Summary     string `yaml:"summary,omitempty"`     // OAS 3.1+
	Description string `yaml:"description,omitempty"` // OAS 3.1+
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Reference represents a JSON Reference ($ref)

type RequestBody

type RequestBody struct {
	Ref         string                 `yaml:"$ref,omitempty"`
	Description string                 `yaml:"description,omitempty"`
	Content     map[string]*MediaType  `yaml:"content"`
	Required    bool                   `yaml:"required,omitempty"`
	Extra       map[string]interface{} `yaml:",inline"`
}

RequestBody describes a single request body (OAS 3.0+)

type Response

type Response struct {
	Ref         string                `yaml:"$ref,omitempty"`
	Description string                `yaml:"description"`
	Headers     map[string]*Header    `yaml:"headers,omitempty"`
	Content     map[string]*MediaType `yaml:"content,omitempty"` // OAS 3.0+
	Links       map[string]*Link      `yaml:"links,omitempty"`   // OAS 3.0+
	// OAS 2.0 specific
	Schema   *Schema                `yaml:"schema,omitempty"`   // OAS 2.0
	Examples map[string]interface{} `yaml:"examples,omitempty"` // OAS 2.0
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Response describes a single response from an API Operation

type Responses

type Responses struct {
	Default *Response            `yaml:"default,omitempty"`
	Codes   map[string]*Response `yaml:",inline"`
}

Responses is a container for the expected responses of an operation

func (*Responses) UnmarshalYAML

func (r *Responses) UnmarshalYAML(unmarshal func(interface{}) 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"`
	Schema string `yaml:"$schema,omitempty"` // JSON Schema Draft version

	// Metadata
	Title       string        `yaml:"title,omitempty"`
	Description string        `yaml:"description,omitempty"`
	Default     interface{}   `yaml:"default,omitempty"`
	Examples    []interface{} `yaml:"examples,omitempty"` // OAS 3.0+, JSON Schema Draft 2020-12

	// Type validation
	Type  interface{}   `yaml:"type,omitempty"` // string or []string (OAS 3.1+)
	Enum  []interface{} `yaml:"enum,omitempty"`
	Const interface{}   `yaml:"const,omitempty"` // JSON Schema Draft 2020-12

	// Numeric validation
	MultipleOf       *float64    `yaml:"multipleOf,omitempty"`
	Maximum          *float64    `yaml:"maximum,omitempty"`
	ExclusiveMaximum interface{} `yaml:"exclusiveMaximum,omitempty"` // bool in OAS 2.0/3.0, number in 3.1+
	Minimum          *float64    `yaml:"minimum,omitempty"`
	ExclusiveMinimum interface{} `yaml:"exclusiveMinimum,omitempty"` // bool in OAS 2.0/3.0, number in 3.1+

	// String validation
	MaxLength *int   `yaml:"maxLength,omitempty"`
	MinLength *int   `yaml:"minLength,omitempty"`
	Pattern   string `yaml:"pattern,omitempty"`

	// Array validation
	Items           interface{} `yaml:"items,omitempty"`           // *Schema or bool (OAS 3.1+)
	PrefixItems     []*Schema   `yaml:"prefixItems,omitempty"`     // JSON Schema Draft 2020-12
	AdditionalItems interface{} `yaml:"additionalItems,omitempty"` // *Schema or bool
	MaxItems        *int        `yaml:"maxItems,omitempty"`
	MinItems        *int        `yaml:"minItems,omitempty"`
	UniqueItems     bool        `yaml:"uniqueItems,omitempty"`
	Contains        *Schema     `yaml:"contains,omitempty"`    // JSON Schema Draft 2020-12
	MaxContains     *int        `yaml:"maxContains,omitempty"` // JSON Schema Draft 2020-12
	MinContains     *int        `yaml:"minContains,omitempty"` // JSON Schema Draft 2020-12

	// Object validation
	Properties           map[string]*Schema  `yaml:"properties,omitempty"`
	PatternProperties    map[string]*Schema  `yaml:"patternProperties,omitempty"`
	AdditionalProperties interface{}         `yaml:"additionalProperties,omitempty"` // *Schema or bool
	Required             []string            `yaml:"required,omitempty"`
	PropertyNames        *Schema             `yaml:"propertyNames,omitempty"` // JSON Schema Draft 2020-12
	MaxProperties        *int                `yaml:"maxProperties,omitempty"`
	MinProperties        *int                `yaml:"minProperties,omitempty"`
	DependentRequired    map[string][]string `yaml:"dependentRequired,omitempty"` // JSON Schema Draft 2020-12
	DependentSchemas     map[string]*Schema  `yaml:"dependentSchemas,omitempty"`  // JSON Schema Draft 2020-12

	// Conditional schemas
	If   *Schema `yaml:"if,omitempty"`   // JSON Schema Draft 2020-12, OAS 3.1+
	Then *Schema `yaml:"then,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+
	Else *Schema `yaml:"else,omitempty"` // JSON Schema Draft 2020-12, OAS 3.1+

	// Schema composition
	AllOf []*Schema `yaml:"allOf,omitempty"`
	AnyOf []*Schema `yaml:"anyOf,omitempty"`
	OneOf []*Schema `yaml:"oneOf,omitempty"`
	Not   *Schema   `yaml:"not,omitempty"`

	// OAS specific extensions
	Nullable      bool           `yaml:"nullable,omitempty"`      // OAS 3.0 only (replaced by type: [T, "null"] in 3.1+)
	Discriminator *Discriminator `yaml:"discriminator,omitempty"` // OAS 3.0+
	ReadOnly      bool           `yaml:"readOnly,omitempty"`      // OAS 2.0+
	WriteOnly     bool           `yaml:"writeOnly,omitempty"`     // OAS 3.0+
	XML           *XML           `yaml:"xml,omitempty"`           // OAS 2.0+
	ExternalDocs  *ExternalDocs  `yaml:"externalDocs,omitempty"`  // OAS 2.0+
	Example       interface{}    `yaml:"example,omitempty"`       // OAS 2.0, 3.0 (deprecated in 3.1+)
	Deprecated    bool           `yaml:"deprecated,omitempty"`    // OAS 3.0+

	// Format
	Format string `yaml:"format,omitempty"` // e.g., "date-time", "email", "uri", etc.

	// OAS 2.0 specific
	CollectionFormat string `yaml:"collectionFormat,omitempty"` // OAS 2.0

	// JSON Schema Draft 2020-12 additional fields
	ID            string             `yaml:"$id,omitempty"`
	Anchor        string             `yaml:"$anchor,omitempty"`
	DynamicRef    string             `yaml:"$dynamicRef,omitempty"`
	DynamicAnchor string             `yaml:"$dynamicAnchor,omitempty"`
	Vocabulary    map[string]bool    `yaml:"$vocabulary,omitempty"`
	Comment       string             `yaml:"$comment,omitempty"`
	Defs          map[string]*Schema `yaml:"$defs,omitempty"`

	// Extension fields
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Schema represents a JSON Schema Supports OAS 2.0, OAS 3.0, OAS 3.1+ (JSON Schema Draft 2020-12)

type SecurityRequirement

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"`
	Type        string `yaml:"type"` // "apiKey", "http", "oauth2", "openIdConnect" (OAS 3.0+), "basic", "apiKey", "oauth2" (OAS 2.0)
	Description string `yaml:"description,omitempty"`

	// Type: apiKey (OAS 2.0+, 3.0+)
	Name string `yaml:"name,omitempty"` // Header, query, or cookie parameter name
	In   string `yaml:"in,omitempty"`   // "query", "header", "cookie" (OAS 3.0+)

	// Type: http (OAS 3.0+)
	Scheme       string `yaml:"scheme,omitempty"`       // e.g., "basic", "bearer"
	BearerFormat string `yaml:"bearerFormat,omitempty"` // e.g., "JWT"

	// Type: oauth2
	Flows *OAuthFlows `yaml:"flows,omitempty"` // OAS 3.0+

	// Type: oauth2 (OAS 2.0)
	Flow             string            `yaml:"flow,omitempty"`             // "implicit", "password", "application", "accessCode"
	AuthorizationURL string            `yaml:"authorizationUrl,omitempty"` // OAS 2.0
	TokenURL         string            `yaml:"tokenUrl,omitempty"`         // OAS 2.0
	Scopes           map[string]string `yaml:"scopes,omitempty"`           // OAS 2.0

	// Type: openIdConnect (OAS 3.0+)
	OpenIDConnectURL string `yaml:"openIdConnectUrl,omitempty"`

	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

SecurityScheme defines a security scheme that can be used by the operations

type Server

type Server struct {
	URL         string                    `yaml:"url"`
	Description string                    `yaml:"description,omitempty"`
	Variables   map[string]ServerVariable `yaml:"variables,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Server represents a Server object (OAS 3.0+)

type ServerVariable

type ServerVariable struct {
	Enum        []string `yaml:"enum,omitempty"`
	Default     string   `yaml:"default"`
	Description string   `yaml:"description,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

ServerVariable represents a Server Variable object (OAS 3.0+)

type SourceFormat added in v1.6.0

type SourceFormat string

SourceFormat represents the format of the source OpenAPI specification file

const (
	// SourceFormatYAML indicates the source was in YAML format
	SourceFormatYAML SourceFormat = "yaml"
	// SourceFormatJSON indicates the source was in JSON format
	SourceFormatJSON SourceFormat = "json"
	// SourceFormatUnknown indicates the source format could not be determined
	SourceFormatUnknown SourceFormat = "unknown"
)

type Tag

type Tag struct {
	Name         string        `yaml:"name"`
	Description  string        `yaml:"description,omitempty"`
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`
	// Extra captures specification extensions (fields starting with "x-")
	Extra map[string]interface{} `yaml:",inline"`
}

Tag adds metadata to a single tag used by operations

type XML

type XML struct {
	Name      string                 `yaml:"name,omitempty"`
	Namespace string                 `yaml:"namespace,omitempty"`
	Prefix    string                 `yaml:"prefix,omitempty"`
	Attribute bool                   `yaml:"attribute,omitempty"`
	Wrapped   bool                   `yaml:"wrapped,omitempty"`
	Extra     map[string]interface{} `yaml:",inline"`
}

XML represents metadata for XML encoding (OAS 2.0+)

Jump to

Keyboard shortcuts

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