kin-openapi: github.com/getkin/kin-openapi/openapi3 Index | Examples | Files

package openapi3

import "github.com/getkin/kin-openapi/openapi3"

Package openapi3 parses and writes OpenAPI 3 specifications.

The OpenAPI 3.0 specification can be found at:

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md

Index

Examples

Package Files

callback.go components.go content.go discriminator.go doc.go encoding.go errors.go examples.go extension.go external_docs.go header.go info.go link.go media_type.go operation.go parameter.go path_item.go paths.go refs.go request_body.go response.go schema.go schema_formats.go schema_validation_settings.go security_requirements.go security_scheme.go serialization_method.go server.go swagger.go swagger_loader.go tag.go

Constants

const (
    ParameterInPath   = "path"
    ParameterInQuery  = "query"
    ParameterInHeader = "header"
    ParameterInCookie = "cookie"
)
const (
    SerializationSimple         = "simple"
    SerializationLabel          = "label"
    SerializationMatrix         = "matrix"
    SerializationForm           = "form"
    SerializationSpaceDelimited = "spaceDelimited"
    SerializationPipeDelimited  = "pipeDelimited"
    SerializationDeepObject     = "deepObject"
)
const (
    // FormatOfStringForUUIDOfRFC4122 is an optional predefined format for UUID v1-v5 as specified by RFC4122
    FormatOfStringForUUIDOfRFC4122 = `^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`
)

Variables

var (
    // SchemaErrorDetailsDisabled disables printing of details about schema errors.
    SchemaErrorDetailsDisabled = false

    //SchemaFormatValidationDisabled disables validation of schema type formats.
    SchemaFormatValidationDisabled = false

    // ErrSchemaInputNaN may be returned when validating a number
    ErrSchemaInputNaN = errors.New("NaN is not allowed")
    // ErrSchemaInputInf may be returned when validating a number
    ErrSchemaInputInf = errors.New("Inf is not allowed")
)
var IdentifierRegExp = regexp.MustCompile(identifierPattern)

IdentifierRegExp verifies whether Component object key matches 'identifierPattern' pattern, according to OapiAPI v3.x.0. Hovever, to be able supporting legacy OpenAPI v2.x, there is a need to customize above pattern in orde not to fail converted v2-v3 validation

var SchemaStringFormats = make(map[string]Format, 8)

SchemaStringFormats allows for validating strings format

func BoolPtr Uses

func BoolPtr(value bool) *bool

BoolPtr is a helper for defining OpenAPI schemas.

func DefineIPv4Format Uses

func DefineIPv4Format()

DefineIPv4Format opts in ipv4 format validation on top of OAS 3 spec

func DefineIPv6Format Uses

func DefineIPv6Format()

DefineIPv6Format opts in ipv6 format validation on top of OAS 3 spec

func DefineStringFormat Uses

func DefineStringFormat(name string, pattern string)

DefineStringFormat Defines a new regexp pattern for a given format

func DefineStringFormatCallback Uses

func DefineStringFormatCallback(name string, callback FormatCallback)

DefineStringFormatCallback adds a validation function for a specific schema format entry

func Float64Ptr Uses

func Float64Ptr(value float64) *float64

Float64Ptr is a helper for defining OpenAPI schemas.

func Int64Ptr Uses

func Int64Ptr(value int64) *int64

Int64Ptr is a helper for defining OpenAPI schemas.

func RegisterArrayUniqueItemsChecker Uses

func RegisterArrayUniqueItemsChecker(fn SliceUniqueItemsChecker)

RegisterArrayUniqueItemsChecker is used to register a customized function used to check if JSON array have unique items.

func Uint64Ptr Uses

func Uint64Ptr(value uint64) *uint64

Uint64Ptr is a helper for defining OpenAPI schemas.

func ValidateIdentifier Uses

func ValidateIdentifier(value string) error

type Callback Uses

type Callback map[string]*PathItem

Callback is specified by OpenAPI/Swagger standard version 3.0.

func (Callback) Validate Uses

func (value Callback) Validate(c context.Context) error

type CallbackRef Uses

type CallbackRef struct {
    Ref   string
    Value *Callback
}

func (*CallbackRef) MarshalJSON Uses

func (value *CallbackRef) MarshalJSON() ([]byte, error)

func (*CallbackRef) UnmarshalJSON Uses

func (value *CallbackRef) UnmarshalJSON(data []byte) error

func (*CallbackRef) Validate Uses

func (value *CallbackRef) Validate(c context.Context) error

type Components Uses

type Components struct {
    ExtensionProps
    Schemas         map[string]*SchemaRef         `json:"schemas,omitempty" yaml:"schemas,omitempty"`
    Parameters      map[string]*ParameterRef      `json:"parameters,omitempty" yaml:"parameters,omitempty"`
    Headers         map[string]*HeaderRef         `json:"headers,omitempty" yaml:"headers,omitempty"`
    RequestBodies   map[string]*RequestBodyRef    `json:"requestBodies,omitempty" yaml:"requestBodies,omitempty"`
    Responses       map[string]*ResponseRef       `json:"responses,omitempty" yaml:"responses,omitempty"`
    SecuritySchemes map[string]*SecuritySchemeRef `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"`
    Examples        map[string]*ExampleRef        `json:"examples,omitempty" yaml:"examples,omitempty"`
    Links           map[string]*LinkRef           `json:"links,omitempty" yaml:"links,omitempty"`
    Callbacks       map[string]*CallbackRef       `json:"callbacks,omitempty" yaml:"callbacks,omitempty"`
}

Components is specified by OpenAPI/Swagger standard version 3.0.

func NewComponents Uses

func NewComponents() Components

func (*Components) MarshalJSON Uses

func (components *Components) MarshalJSON() ([]byte, error)

func (*Components) UnmarshalJSON Uses

func (components *Components) UnmarshalJSON(data []byte) error

func (*Components) Validate Uses

func (components *Components) Validate(c context.Context) (err error)

type Contact Uses

type Contact struct {
    ExtensionProps
    Name  string `json:"name,omitempty" yaml:"name,omitempty"`
    URL   string `json:"url,omitempty" yaml:"url,omitempty"`
    Email string `json:"email,omitempty" yaml:"email,omitempty"`
}

Contact is specified by OpenAPI/Swagger standard version 3.0.

func (*Contact) MarshalJSON Uses

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

func (*Contact) UnmarshalJSON Uses

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

func (*Contact) Validate Uses

func (value *Contact) Validate(c context.Context) error

type Content Uses

type Content map[string]*MediaType

Content is specified by OpenAPI/Swagger 3.0 standard.

func NewContent Uses

func NewContent() Content

func NewContentWithFormDataSchema Uses

func NewContentWithFormDataSchema(schema *Schema) Content

func NewContentWithFormDataSchemaRef Uses

func NewContentWithFormDataSchemaRef(schema *SchemaRef) Content

func NewContentWithJSONSchema Uses

func NewContentWithJSONSchema(schema *Schema) Content

func NewContentWithJSONSchemaRef Uses

func NewContentWithJSONSchemaRef(schema *SchemaRef) Content

func NewContentWithSchema Uses

func NewContentWithSchema(schema *Schema, consumes []string) Content

func NewContentWithSchemaRef Uses

func NewContentWithSchemaRef(schema *SchemaRef, consumes []string) Content

func (Content) Get Uses

func (content Content) Get(mime string) *MediaType

func (Content) Validate Uses

func (content Content) Validate(c context.Context) error

type Discriminator Uses

type Discriminator struct {
    ExtensionProps
    PropertyName string            `json:"propertyName" yaml:"propertyName"`
    Mapping      map[string]string `json:"mapping,omitempty" yaml:"mapping,omitempty"`
}

Discriminator is specified by OpenAPI/Swagger standard version 3.0.

func (*Discriminator) MarshalJSON Uses

func (value *Discriminator) MarshalJSON() ([]byte, error)

func (*Discriminator) UnmarshalJSON Uses

func (value *Discriminator) UnmarshalJSON(data []byte) error

func (*Discriminator) Validate Uses

func (value *Discriminator) Validate(c context.Context) error

type Encoding Uses

type Encoding struct {
    ExtensionProps

    ContentType   string                `json:"contentType,omitempty" yaml:"contentType,omitempty"`
    Headers       map[string]*HeaderRef `json:"headers,omitempty" yaml:"headers,omitempty"`
    Style         string                `json:"style,omitempty" yaml:"style,omitempty"`
    Explode       *bool                 `json:"explode,omitempty" yaml:"explode,omitempty"`
    AllowReserved bool                  `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"`
}

Encoding is specified by OpenAPI/Swagger 3.0 standard.

func NewEncoding Uses

func NewEncoding() *Encoding

func (*Encoding) MarshalJSON Uses

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

func (*Encoding) SerializationMethod Uses

func (encoding *Encoding) SerializationMethod() *SerializationMethod

SerializationMethod returns a serialization method of request body. When serialization method is not defined the method returns the default serialization method.

func (*Encoding) UnmarshalJSON Uses

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

func (*Encoding) Validate Uses

func (encoding *Encoding) Validate(c context.Context) error

func (*Encoding) WithHeader Uses

func (encoding *Encoding) WithHeader(name string, header *Header) *Encoding

func (*Encoding) WithHeaderRef Uses

func (encoding *Encoding) WithHeaderRef(name string, ref *HeaderRef) *Encoding

type Example Uses

type Example struct {
    ExtensionProps

    Summary       string      `json:"summary,omitempty" yaml:"summary,omitempty"`
    Description   string      `json:"description,omitempty" yaml:"description,omitempty"`
    Value         interface{} `json:"value,omitempty" yaml:"value,omitempty"`
    ExternalValue string      `json:"externalValue,omitempty" yaml:"externalValue,omitempty"`
}

Example is specified by OpenAPI/Swagger 3.0 standard.

func NewExample Uses

func NewExample(value interface{}) *Example

func (*Example) MarshalJSON Uses

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

func (*Example) UnmarshalJSON Uses

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

type ExampleRef Uses

type ExampleRef struct {
    Ref   string
    Value *Example
}

func (*ExampleRef) MarshalJSON Uses

func (value *ExampleRef) MarshalJSON() ([]byte, error)

func (*ExampleRef) UnmarshalJSON Uses

func (value *ExampleRef) UnmarshalJSON(data []byte) error

func (*ExampleRef) Validate Uses

func (value *ExampleRef) Validate(c context.Context) error

type ExtensionProps Uses

type ExtensionProps struct {
    Extensions map[string]interface{} `json:"-" yaml:"-"`
}

ExtensionProps provides support for OpenAPI extensions. It reads/writes all properties that begin with "x-".

func (*ExtensionProps) DecodeWith Uses

func (props *ExtensionProps) DecodeWith(decoder *jsoninfo.ObjectDecoder, value interface{}) error

DecodeWith will be invoked by package "jsoninfo"

func (*ExtensionProps) EncodeWith Uses

func (props *ExtensionProps) EncodeWith(encoder *jsoninfo.ObjectEncoder, value interface{}) error

EncodeWith will be invoked by package "jsoninfo"

type ExternalDocs Uses

type ExternalDocs struct {
    ExtensionProps

    Description string `json:"description,omitempty"`
    URL         string `json:"url,omitempty"`
}

ExternalDocs is specified by OpenAPI/Swagger standard version 3.0.

func (*ExternalDocs) MarshalJSON Uses

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

func (*ExternalDocs) UnmarshalJSON Uses

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

type Format Uses

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

type FormatCallback Uses

type FormatCallback func(Val string) error

FormatCallback custom check on exotic formats

type Header struct {
    ExtensionProps

    // Optional description. Should use CommonMark syntax.
    Description string                 `json:"description,omitempty" yaml:"description,omitempty"`
    Deprecated  bool                   `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
    Required    bool                   `json:"required,omitempty" yaml:"required,omitempty"`
    Schema      *SchemaRef             `json:"schema,omitempty" yaml:"schema,omitempty"`
    Example     interface{}            `json:"example,omitempty" yaml:"example,omitempty"`
    Examples    map[string]*ExampleRef `json:"examples,omitempty" yaml:"examples,omitempty"`
    Content     Content                `json:"content,omitempty" yaml:"content,omitempty"`
}

func (*Header) UnmarshalJSON Uses

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

func (*Header) Validate Uses

func (value *Header) Validate(c context.Context) error

type HeaderRef Uses

type HeaderRef struct {
    Ref   string
    Value *Header
}

func (*HeaderRef) MarshalJSON Uses

func (value *HeaderRef) MarshalJSON() ([]byte, error)

func (*HeaderRef) UnmarshalJSON Uses

func (value *HeaderRef) UnmarshalJSON(data []byte) error

func (*HeaderRef) Validate Uses

func (value *HeaderRef) Validate(c context.Context) error

type Info Uses

type Info struct {
    ExtensionProps
    Title          string   `json:"title" yaml:"title"` // Required
    Description    string   `json:"description,omitempty" yaml:"description,omitempty"`
    TermsOfService string   `json:"termsOfService,omitempty" yaml:"termsOfService,omitempty"`
    Contact        *Contact `json:"contact,omitempty" yaml:"contact,omitempty"`
    License        *License `json:"license,omitempty" yaml:"license,omitempty"`
    Version        string   `json:"version" yaml:"version"` // Required
}

Info is specified by OpenAPI/Swagger standard version 3.0.

func (*Info) MarshalJSON Uses

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

func (*Info) UnmarshalJSON Uses

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

func (*Info) Validate Uses

func (value *Info) Validate(c context.Context) error

type License Uses

type License struct {
    ExtensionProps
    Name string `json:"name" yaml:"name"` // Required
    URL  string `json:"url,omitempty" yaml:"url,omitempty"`
}

License is specified by OpenAPI/Swagger standard version 3.0.

func (*License) MarshalJSON Uses

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

func (*License) UnmarshalJSON Uses

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

func (*License) Validate Uses

func (value *License) Validate(c context.Context) error
type Link struct {
    ExtensionProps
    OperationID  string                 `json:"operationId,omitempty" yaml:"operationId,omitempty"`
    OperationRef string                 `json:"operationRef,omitempty" yaml:"operationRef,omitempty"`
    Description  string                 `json:"description,omitempty" yaml:"description,omitempty"`
    Parameters   map[string]interface{} `json:"parameters,omitempty" yaml:"parameters,omitempty"`
    Server       *Server                `json:"server,omitempty" yaml:"server,omitempty"`
    RequestBody  interface{}            `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`
}

Link is specified by OpenAPI/Swagger standard version 3.0.

func (*Link) MarshalJSON Uses

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

func (*Link) UnmarshalJSON Uses

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

func (*Link) Validate Uses

func (value *Link) Validate(c context.Context) error

type LinkRef Uses

type LinkRef struct {
    Ref   string
    Value *Link
}

func (*LinkRef) MarshalJSON Uses

func (value *LinkRef) MarshalJSON() ([]byte, error)

func (*LinkRef) UnmarshalJSON Uses

func (value *LinkRef) UnmarshalJSON(data []byte) error

func (*LinkRef) Validate Uses

func (value *LinkRef) Validate(c context.Context) error

type MediaType Uses

type MediaType struct {
    ExtensionProps

    Schema   *SchemaRef             `json:"schema,omitempty" yaml:"schema,omitempty"`
    Example  interface{}            `json:"example,omitempty" yaml:"example,omitempty"`
    Examples map[string]*ExampleRef `json:"examples,omitempty" yaml:"examples,omitempty"`
    Encoding map[string]*Encoding   `json:"encoding,omitempty" yaml:"encoding,omitempty"`
}

MediaType is specified by OpenAPI/Swagger 3.0 standard.

func NewMediaType Uses

func NewMediaType() *MediaType

func (*MediaType) MarshalJSON Uses

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

func (*MediaType) UnmarshalJSON Uses

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

func (*MediaType) Validate Uses

func (mediaType *MediaType) Validate(c context.Context) error

func (*MediaType) WithEncoding Uses

func (mediaType *MediaType) WithEncoding(name string, enc *Encoding) *MediaType

func (*MediaType) WithExample Uses

func (mediaType *MediaType) WithExample(name string, value interface{}) *MediaType

func (*MediaType) WithSchema Uses

func (mediaType *MediaType) WithSchema(schema *Schema) *MediaType

func (*MediaType) WithSchemaRef Uses

func (mediaType *MediaType) WithSchemaRef(schema *SchemaRef) *MediaType

type MultiError Uses

type MultiError []error

MultiError is a collection of errors, intended for when multiple issues need to be reported upstream

func (MultiError) As Uses

func (me MultiError) As(target interface{}) bool

As allows you to use `errors.As()` to set target to the first error within the multi error that matches the target type

func (MultiError) Error Uses

func (me MultiError) Error() string

func (MultiError) Is Uses

func (me MultiError) Is(target error) bool

Is allows you to determine if a generic error is in fact a MultiError using `errors.Is()` It will also return true if any of the contained errors match target

type OAuthFlow Uses

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

func (*OAuthFlow) MarshalJSON Uses

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

func (*OAuthFlow) UnmarshalJSON Uses

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

func (*OAuthFlow) Validate Uses

func (flow *OAuthFlow) Validate(c context.Context, typ oAuthFlowType) error

type OAuthFlows Uses

type OAuthFlows struct {
    ExtensionProps
    Implicit          *OAuthFlow `json:"implicit,omitempty" yaml:"implicit,omitempty"`
    Password          *OAuthFlow `json:"password,omitempty" yaml:"password,omitempty"`
    ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty" yaml:"clientCredentials,omitempty"`
    AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty" yaml:"authorizationCode,omitempty"`
}

func (*OAuthFlows) MarshalJSON Uses

func (flows *OAuthFlows) MarshalJSON() ([]byte, error)

func (*OAuthFlows) UnmarshalJSON Uses

func (flows *OAuthFlows) UnmarshalJSON(data []byte) error

func (*OAuthFlows) Validate Uses

func (flows *OAuthFlows) Validate(c context.Context) error

type Operation Uses

type Operation struct {
    ExtensionProps

    // Optional tags for documentation.
    Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"`

    // Optional short summary.
    Summary string `json:"summary,omitempty" yaml:"summary,omitempty"`

    // Optional description. Should use CommonMark syntax.
    Description string `json:"description,omitempty" yaml:"description,omitempty"`

    // Optional operation ID.
    OperationID string `json:"operationId,omitempty" yaml:"operationId,omitempty"`

    // Optional parameters.
    Parameters Parameters `json:"parameters,omitempty" yaml:"parameters,omitempty"`

    // Optional body parameter.
    RequestBody *RequestBodyRef `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`

    // Responses.
    Responses Responses `json:"responses" yaml:"responses"` // Required

    // Optional callbacks
    Callbacks map[string]*CallbackRef `json:"callbacks,omitempty" yaml:"callbacks,omitempty"`

    Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`

    // Optional security requirements that overrides top-level security.
    Security *SecurityRequirements `json:"security,omitempty" yaml:"security,omitempty"`

    // Optional servers that overrides top-level servers.
    Servers *Servers `json:"servers,omitempty" yaml:"servers,omitempty"`

    ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

Operation represents "operation" specified by" OpenAPI/Swagger 3.0 standard.

func NewOperation Uses

func NewOperation() *Operation

func (*Operation) AddParameter Uses

func (operation *Operation) AddParameter(p *Parameter)

func (*Operation) AddResponse Uses

func (operation *Operation) AddResponse(status int, response *Response)

func (*Operation) MarshalJSON Uses

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

func (*Operation) UnmarshalJSON Uses

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

func (*Operation) Validate Uses

func (operation *Operation) Validate(c context.Context) error

type Parameter Uses

type Parameter struct {
    ExtensionProps
    Name            string                 `json:"name,omitempty" yaml:"name,omitempty"`
    In              string                 `json:"in,omitempty" yaml:"in,omitempty"`
    Description     string                 `json:"description,omitempty" yaml:"description,omitempty"`
    Style           string                 `json:"style,omitempty" yaml:"style,omitempty"`
    Explode         *bool                  `json:"explode,omitempty" yaml:"explode,omitempty"`
    AllowEmptyValue bool                   `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
    AllowReserved   bool                   `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"`
    Deprecated      bool                   `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
    Required        bool                   `json:"required,omitempty" yaml:"required,omitempty"`
    Schema          *SchemaRef             `json:"schema,omitempty" yaml:"schema,omitempty"`
    Example         interface{}            `json:"example,omitempty" yaml:"example,omitempty"`
    Examples        map[string]*ExampleRef `json:"examples,omitempty" yaml:"examples,omitempty"`
    Content         Content                `json:"content,omitempty" yaml:"content,omitempty"`
}

Parameter is specified by OpenAPI/Swagger 3.0 standard.

func NewCookieParameter Uses

func NewCookieParameter(name string) *Parameter

func NewHeaderParameter Uses

func NewHeaderParameter(name string) *Parameter

func NewPathParameter Uses

func NewPathParameter(name string) *Parameter

func NewQueryParameter Uses

func NewQueryParameter(name string) *Parameter

func (*Parameter) MarshalJSON Uses

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

func (*Parameter) SerializationMethod Uses

func (parameter *Parameter) SerializationMethod() (*SerializationMethod, error)

SerializationMethod returns a parameter's serialization method. When a parameter's serialization method is not defined the method returns the default serialization method corresponding to a parameter's location.

func (*Parameter) UnmarshalJSON Uses

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

func (*Parameter) Validate Uses

func (parameter *Parameter) Validate(c context.Context) error

func (*Parameter) WithDescription Uses

func (parameter *Parameter) WithDescription(value string) *Parameter

func (*Parameter) WithRequired Uses

func (parameter *Parameter) WithRequired(value bool) *Parameter

func (*Parameter) WithSchema Uses

func (parameter *Parameter) WithSchema(value *Schema) *Parameter

type ParameterRef Uses

type ParameterRef struct {
    Ref   string
    Value *Parameter
}

func (*ParameterRef) MarshalJSON Uses

func (value *ParameterRef) MarshalJSON() ([]byte, error)

func (*ParameterRef) UnmarshalJSON Uses

func (value *ParameterRef) UnmarshalJSON(data []byte) error

func (*ParameterRef) Validate Uses

func (value *ParameterRef) Validate(c context.Context) error

type Parameters Uses

type Parameters []*ParameterRef

Parameters is specified by OpenAPI/Swagger 3.0 standard.

func NewParameters Uses

func NewParameters() Parameters

func (Parameters) GetByInAndName Uses

func (parameters Parameters) GetByInAndName(in string, name string) *Parameter

func (Parameters) Validate Uses

func (parameters Parameters) Validate(c context.Context) error

type PathItem Uses

type PathItem struct {
    ExtensionProps
    Ref         string     `json:"$ref,omitempty" yaml:"$ref,omitempty"`
    Summary     string     `json:"summary,omitempty" yaml:"summary,omitempty"`
    Description string     `json:"description,omitempty" yaml:"description,omitempty"`
    Connect     *Operation `json:"connect,omitempty" yaml:"connect,omitempty"`
    Delete      *Operation `json:"delete,omitempty" yaml:"delete,omitempty"`
    Get         *Operation `json:"get,omitempty" yaml:"get,omitempty"`
    Head        *Operation `json:"head,omitempty" yaml:"head,omitempty"`
    Options     *Operation `json:"options,omitempty" yaml:"options,omitempty"`
    Patch       *Operation `json:"patch,omitempty" yaml:"patch,omitempty"`
    Post        *Operation `json:"post,omitempty" yaml:"post,omitempty"`
    Put         *Operation `json:"put,omitempty" yaml:"put,omitempty"`
    Trace       *Operation `json:"trace,omitempty" yaml:"trace,omitempty"`
    Servers     Servers    `json:"servers,omitempty" yaml:"servers,omitempty"`
    Parameters  Parameters `json:"parameters,omitempty" yaml:"parameters,omitempty"`
}

func (*PathItem) GetOperation Uses

func (pathItem *PathItem) GetOperation(method string) *Operation

func (*PathItem) MarshalJSON Uses

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

func (*PathItem) Operations Uses

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

func (*PathItem) SetOperation Uses

func (pathItem *PathItem) SetOperation(method string, operation *Operation)

func (*PathItem) UnmarshalJSON Uses

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

func (*PathItem) Validate Uses

func (pathItem *PathItem) Validate(c context.Context) error

type Paths Uses

type Paths map[string]*PathItem

Paths is specified by OpenAPI/Swagger standard version 3.0.

func (Paths) Find Uses

func (paths Paths) Find(key string) *PathItem

Find returns a path that matches the key.

The method ignores differences in template variable names (except possible "*" suffix).

For example:

paths := openapi3.Paths {
  "/person/{personName}": &openapi3.PathItem{},
}
pathItem := path.Find("/person/{name}")

would return the correct path item.

func (Paths) Validate Uses

func (paths Paths) Validate(c context.Context) error

type RequestBody Uses

type RequestBody struct {
    ExtensionProps
    Description string  `json:"description,omitempty" yaml:"description,omitempty"`
    Required    bool    `json:"required,omitempty" yaml:"required,omitempty"`
    Content     Content `json:"content,omitempty" yaml:"content,omitempty"`
}

RequestBody is specified by OpenAPI/Swagger 3.0 standard.

func NewRequestBody Uses

func NewRequestBody() *RequestBody

func (*RequestBody) GetMediaType Uses

func (requestBody *RequestBody) GetMediaType(mediaType string) *MediaType

func (*RequestBody) MarshalJSON Uses

func (requestBody *RequestBody) MarshalJSON() ([]byte, error)

func (*RequestBody) UnmarshalJSON Uses

func (requestBody *RequestBody) UnmarshalJSON(data []byte) error

func (*RequestBody) Validate Uses

func (requestBody *RequestBody) Validate(c context.Context) error

func (*RequestBody) WithContent Uses

func (requestBody *RequestBody) WithContent(content Content) *RequestBody

func (*RequestBody) WithDescription Uses

func (requestBody *RequestBody) WithDescription(value string) *RequestBody

func (*RequestBody) WithFormDataSchema Uses

func (requestBody *RequestBody) WithFormDataSchema(value *Schema) *RequestBody

func (*RequestBody) WithFormDataSchemaRef Uses

func (requestBody *RequestBody) WithFormDataSchemaRef(value *SchemaRef) *RequestBody

func (*RequestBody) WithJSONSchema Uses

func (requestBody *RequestBody) WithJSONSchema(value *Schema) *RequestBody

func (*RequestBody) WithJSONSchemaRef Uses

func (requestBody *RequestBody) WithJSONSchemaRef(value *SchemaRef) *RequestBody

func (*RequestBody) WithRequired Uses

func (requestBody *RequestBody) WithRequired(value bool) *RequestBody

func (*RequestBody) WithSchema Uses

func (requestBody *RequestBody) WithSchema(value *Schema, consumes []string) *RequestBody

func (*RequestBody) WithSchemaRef Uses

func (requestBody *RequestBody) WithSchemaRef(value *SchemaRef, consumes []string) *RequestBody

type RequestBodyRef Uses

type RequestBodyRef struct {
    Ref   string
    Value *RequestBody
}

func (*RequestBodyRef) MarshalJSON Uses

func (value *RequestBodyRef) MarshalJSON() ([]byte, error)

func (*RequestBodyRef) UnmarshalJSON Uses

func (value *RequestBodyRef) UnmarshalJSON(data []byte) error

func (*RequestBodyRef) Validate Uses

func (value *RequestBodyRef) Validate(c context.Context) error

type Response Uses

type Response struct {
    ExtensionProps
    Description *string               `json:"description,omitempty" yaml:"description,omitempty"`
    Headers     map[string]*HeaderRef `json:"headers,omitempty" yaml:"headers,omitempty"`
    Content     Content               `json:"content,omitempty" yaml:"content,omitempty"`
    Links       map[string]*LinkRef   `json:"links,omitempty" yaml:"links,omitempty"`
}

Response is specified by OpenAPI/Swagger 3.0 standard.

func NewResponse Uses

func NewResponse() *Response

func (*Response) MarshalJSON Uses

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

func (*Response) UnmarshalJSON Uses

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

func (*Response) Validate Uses

func (response *Response) Validate(c context.Context) error

func (*Response) WithContent Uses

func (response *Response) WithContent(content Content) *Response

func (*Response) WithDescription Uses

func (response *Response) WithDescription(value string) *Response

func (*Response) WithJSONSchema Uses

func (response *Response) WithJSONSchema(schema *Schema) *Response

func (*Response) WithJSONSchemaRef Uses

func (response *Response) WithJSONSchemaRef(schema *SchemaRef) *Response

type ResponseRef Uses

type ResponseRef struct {
    Ref   string
    Value *Response
}

func (*ResponseRef) MarshalJSON Uses

func (value *ResponseRef) MarshalJSON() ([]byte, error)

func (*ResponseRef) UnmarshalJSON Uses

func (value *ResponseRef) UnmarshalJSON(data []byte) error

func (*ResponseRef) Validate Uses

func (value *ResponseRef) Validate(c context.Context) error

type Responses Uses

type Responses map[string]*ResponseRef

Responses is specified by OpenAPI/Swagger 3.0 standard.

func NewResponses Uses

func NewResponses() Responses

func (Responses) Default Uses

func (responses Responses) Default() *ResponseRef

func (Responses) Get Uses

func (responses Responses) Get(status int) *ResponseRef

func (Responses) Validate Uses

func (responses Responses) Validate(c context.Context) error

type Schema Uses

type Schema struct {
    ExtensionProps

    OneOf        []*SchemaRef  `json:"oneOf,omitempty" yaml:"oneOf,omitempty"`
    AnyOf        []*SchemaRef  `json:"anyOf,omitempty" yaml:"anyOf,omitempty"`
    AllOf        []*SchemaRef  `json:"allOf,omitempty" yaml:"allOf,omitempty"`
    Not          *SchemaRef    `json:"not,omitempty" yaml:"not,omitempty"`
    Type         string        `json:"type,omitempty" yaml:"type,omitempty"`
    Title        string        `json:"title,omitempty" yaml:"title,omitempty"`
    Format       string        `json:"format,omitempty" yaml:"format,omitempty"`
    Description  string        `json:"description,omitempty" yaml:"description,omitempty"`
    Enum         []interface{} `json:"enum,omitempty" yaml:"enum,omitempty"`
    Default      interface{}   `json:"default,omitempty" yaml:"default,omitempty"`
    Example      interface{}   `json:"example,omitempty" yaml:"example,omitempty"`
    ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`

    // Object-related, here for struct compactness
    AdditionalPropertiesAllowed *bool `json:"-" multijson:"additionalProperties,omitempty" yaml:"-"`
    // Array-related, here for struct compactness
    UniqueItems bool `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty"`
    // Number-related, here for struct compactness
    ExclusiveMin bool `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty"`
    ExclusiveMax bool `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty"`
    // Properties
    Nullable        bool        `json:"nullable,omitempty" yaml:"nullable,omitempty"`
    ReadOnly        bool        `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`
    WriteOnly       bool        `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"`
    AllowEmptyValue bool        `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
    XML             interface{} `json:"xml,omitempty" yaml:"xml,omitempty"`
    Deprecated      bool        `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`

    // Number
    Min        *float64 `json:"minimum,omitempty" yaml:"minimum,omitempty"`
    Max        *float64 `json:"maximum,omitempty" yaml:"maximum,omitempty"`
    MultipleOf *float64 `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"`

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

    // Array
    MinItems uint64     `json:"minItems,omitempty" yaml:"minItems,omitempty"`
    MaxItems *uint64    `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
    Items    *SchemaRef `json:"items,omitempty" yaml:"items,omitempty"`

    // Object
    Required             []string              `json:"required,omitempty" yaml:"required,omitempty"`
    Properties           map[string]*SchemaRef `json:"properties,omitempty" yaml:"properties,omitempty"`
    MinProps             uint64                `json:"minProperties,omitempty" yaml:"minProperties,omitempty"`
    MaxProps             *uint64               `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"`
    AdditionalProperties *SchemaRef            `json:"-" multijson:"additionalProperties,omitempty" yaml:"-"`
    Discriminator        *Discriminator        `json:"discriminator,omitempty" yaml:"discriminator,omitempty"`
    // contains filtered or unexported fields
}

Schema is specified by OpenAPI/Swagger 3.0 standard.

func NewAllOfSchema Uses

func NewAllOfSchema(schemas ...*Schema) *Schema

func NewAnyOfSchema Uses

func NewAnyOfSchema(schemas ...*Schema) *Schema

func NewArraySchema Uses

func NewArraySchema() *Schema

func NewBoolSchema Uses

func NewBoolSchema() *Schema

func NewBytesSchema Uses

func NewBytesSchema() *Schema

func NewDateTimeSchema Uses

func NewDateTimeSchema() *Schema

func NewFloat64Schema Uses

func NewFloat64Schema() *Schema

func NewInt32Schema Uses

func NewInt32Schema() *Schema

func NewInt64Schema Uses

func NewInt64Schema() *Schema

func NewIntegerSchema Uses

func NewIntegerSchema() *Schema

func NewObjectSchema Uses

func NewObjectSchema() *Schema

func NewOneOfSchema Uses

func NewOneOfSchema(schemas ...*Schema) *Schema

func NewSchema Uses

func NewSchema() *Schema

func NewStringSchema Uses

func NewStringSchema() *Schema

func NewUUIDSchema Uses

func NewUUIDSchema() *Schema

func (*Schema) IsEmpty Uses

func (schema *Schema) IsEmpty() bool

func (*Schema) IsMatching Uses

func (schema *Schema) IsMatching(value interface{}) bool

func (*Schema) IsMatchingJSONArray Uses

func (schema *Schema) IsMatchingJSONArray(value []interface{}) bool

func (*Schema) IsMatchingJSONBoolean Uses

func (schema *Schema) IsMatchingJSONBoolean(value bool) bool

func (*Schema) IsMatchingJSONNumber Uses

func (schema *Schema) IsMatchingJSONNumber(value float64) bool

func (*Schema) IsMatchingJSONObject Uses

func (schema *Schema) IsMatchingJSONObject(value map[string]interface{}) bool

func (*Schema) IsMatchingJSONString Uses

func (schema *Schema) IsMatchingJSONString(value string) bool

func (*Schema) MarshalJSON Uses

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

func (*Schema) NewRef Uses

func (schema *Schema) NewRef() *SchemaRef

func (*Schema) UnmarshalJSON Uses

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

func (*Schema) Validate Uses

func (schema *Schema) Validate(c context.Context) error

func (*Schema) VisitJSON Uses

func (schema *Schema) VisitJSON(value interface{}, opts ...SchemaValidationOption) error

func (*Schema) VisitJSONArray Uses

func (schema *Schema) VisitJSONArray(value []interface{}) error

func (*Schema) VisitJSONBoolean Uses

func (schema *Schema) VisitJSONBoolean(value bool) error

func (*Schema) VisitJSONNumber Uses

func (schema *Schema) VisitJSONNumber(value float64) error

func (*Schema) VisitJSONObject Uses

func (schema *Schema) VisitJSONObject(value map[string]interface{}) error

func (*Schema) VisitJSONString Uses

func (schema *Schema) VisitJSONString(value string) error

func (*Schema) WithAdditionalProperties Uses

func (schema *Schema) WithAdditionalProperties(v *Schema) *Schema

func (*Schema) WithAnyAdditionalProperties Uses

func (schema *Schema) WithAnyAdditionalProperties() *Schema

func (*Schema) WithDefault Uses

func (schema *Schema) WithDefault(defaultValue interface{}) *Schema

func (*Schema) WithEnum Uses

func (schema *Schema) WithEnum(values ...interface{}) *Schema

func (*Schema) WithExclusiveMax Uses

func (schema *Schema) WithExclusiveMax(value bool) *Schema

func (*Schema) WithExclusiveMin Uses

func (schema *Schema) WithExclusiveMin(value bool) *Schema

func (*Schema) WithFormat Uses

func (schema *Schema) WithFormat(value string) *Schema

func (*Schema) WithItems Uses

func (schema *Schema) WithItems(value *Schema) *Schema

func (*Schema) WithLength Uses

func (schema *Schema) WithLength(i int64) *Schema

func (*Schema) WithLengthDecodedBase64 Uses

func (schema *Schema) WithLengthDecodedBase64(i int64) *Schema

func (*Schema) WithMax Uses

func (schema *Schema) WithMax(value float64) *Schema

func (*Schema) WithMaxItems Uses

func (schema *Schema) WithMaxItems(i int64) *Schema

func (*Schema) WithMaxLength Uses

func (schema *Schema) WithMaxLength(i int64) *Schema

func (*Schema) WithMaxLengthDecodedBase64 Uses

func (schema *Schema) WithMaxLengthDecodedBase64(i int64) *Schema

func (*Schema) WithMaxProperties Uses

func (schema *Schema) WithMaxProperties(i int64) *Schema

func (*Schema) WithMin Uses

func (schema *Schema) WithMin(value float64) *Schema

func (*Schema) WithMinItems Uses

func (schema *Schema) WithMinItems(i int64) *Schema

func (*Schema) WithMinLength Uses

func (schema *Schema) WithMinLength(i int64) *Schema

func (*Schema) WithMinLengthDecodedBase64 Uses

func (schema *Schema) WithMinLengthDecodedBase64(i int64) *Schema

func (*Schema) WithMinProperties Uses

func (schema *Schema) WithMinProperties(i int64) *Schema

func (*Schema) WithNullable Uses

func (schema *Schema) WithNullable() *Schema

func (*Schema) WithPattern Uses

func (schema *Schema) WithPattern(pattern string) *Schema

func (*Schema) WithProperties Uses

func (schema *Schema) WithProperties(properties map[string]*Schema) *Schema

func (*Schema) WithProperty Uses

func (schema *Schema) WithProperty(name string, propertySchema *Schema) *Schema

func (*Schema) WithPropertyRef Uses

func (schema *Schema) WithPropertyRef(name string, ref *SchemaRef) *Schema

func (*Schema) WithUniqueItems Uses

func (schema *Schema) WithUniqueItems(unique bool) *Schema

type SchemaError Uses

type SchemaError struct {
    Value interface{}

    Schema      *Schema
    SchemaField string
    Reason      string
    Origin      error
    // contains filtered or unexported fields
}

func (*SchemaError) Error Uses

func (err *SchemaError) Error() string

func (*SchemaError) JSONPointer Uses

func (err *SchemaError) JSONPointer() []string

type SchemaRef Uses

type SchemaRef struct {
    Ref   string
    Value *Schema
}

func NewSchemaRef Uses

func NewSchemaRef(ref string, value *Schema) *SchemaRef

func (*SchemaRef) MarshalJSON Uses

func (value *SchemaRef) MarshalJSON() ([]byte, error)

func (*SchemaRef) UnmarshalJSON Uses

func (value *SchemaRef) UnmarshalJSON(data []byte) error

func (*SchemaRef) Validate Uses

func (value *SchemaRef) Validate(c context.Context) error

type SchemaValidationOption Uses

type SchemaValidationOption func(*schemaValidationSettings)

SchemaValidationOption describes options a user has when validating request / response bodies.

func FailFast Uses

func FailFast() SchemaValidationOption

FailFast returns schema validation errors quicker.

func MultiErrors Uses

func MultiErrors() SchemaValidationOption

func VisitAsRequest Uses

func VisitAsRequest() SchemaValidationOption

func VisitAsResponse Uses

func VisitAsResponse() SchemaValidationOption

type SecurityRequirement Uses

type SecurityRequirement map[string][]string

func NewSecurityRequirement Uses

func NewSecurityRequirement() SecurityRequirement

func (SecurityRequirement) Authenticate Uses

func (security SecurityRequirement) Authenticate(provider string, scopes ...string) SecurityRequirement

func (SecurityRequirement) Validate Uses

func (security SecurityRequirement) Validate(c context.Context) error

type SecurityRequirements Uses

type SecurityRequirements []SecurityRequirement

func NewSecurityRequirements Uses

func NewSecurityRequirements() *SecurityRequirements

func (SecurityRequirements) Validate Uses

func (srs SecurityRequirements) Validate(c context.Context) error

func (*SecurityRequirements) With Uses

func (srs *SecurityRequirements) With(securityRequirement SecurityRequirement) *SecurityRequirements

type SecurityScheme Uses

type SecurityScheme struct {
    ExtensionProps

    Type         string      `json:"type,omitempty" yaml:"type,omitempty"`
    Description  string      `json:"description,omitempty" yaml:"description,omitempty"`
    Name         string      `json:"name,omitempty" yaml:"name,omitempty"`
    In           string      `json:"in,omitempty" yaml:"in,omitempty"`
    Scheme       string      `json:"scheme,omitempty" yaml:"scheme,omitempty"`
    BearerFormat string      `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"`
    Flows        *OAuthFlows `json:"flows,omitempty" yaml:"flows,omitempty"`
}

func NewCSRFSecurityScheme Uses

func NewCSRFSecurityScheme() *SecurityScheme

func NewJWTSecurityScheme Uses

func NewJWTSecurityScheme() *SecurityScheme

func NewSecurityScheme Uses

func NewSecurityScheme() *SecurityScheme

func (*SecurityScheme) MarshalJSON Uses

func (ss *SecurityScheme) MarshalJSON() ([]byte, error)

func (*SecurityScheme) UnmarshalJSON Uses

func (ss *SecurityScheme) UnmarshalJSON(data []byte) error

func (*SecurityScheme) Validate Uses

func (ss *SecurityScheme) Validate(c context.Context) error

func (*SecurityScheme) WithBearerFormat Uses

func (ss *SecurityScheme) WithBearerFormat(value string) *SecurityScheme

func (*SecurityScheme) WithDescription Uses

func (ss *SecurityScheme) WithDescription(value string) *SecurityScheme

func (*SecurityScheme) WithIn Uses

func (ss *SecurityScheme) WithIn(value string) *SecurityScheme

func (*SecurityScheme) WithName Uses

func (ss *SecurityScheme) WithName(value string) *SecurityScheme

func (*SecurityScheme) WithScheme Uses

func (ss *SecurityScheme) WithScheme(value string) *SecurityScheme

func (*SecurityScheme) WithType Uses

func (ss *SecurityScheme) WithType(value string) *SecurityScheme

type SecuritySchemeRef Uses

type SecuritySchemeRef struct {
    Ref   string
    Value *SecurityScheme
}

func (*SecuritySchemeRef) MarshalJSON Uses

func (value *SecuritySchemeRef) MarshalJSON() ([]byte, error)

func (*SecuritySchemeRef) UnmarshalJSON Uses

func (value *SecuritySchemeRef) UnmarshalJSON(data []byte) error

func (*SecuritySchemeRef) Validate Uses

func (value *SecuritySchemeRef) Validate(c context.Context) error

type SerializationMethod Uses

type SerializationMethod struct {
    Style   string
    Explode bool
}

SerializationMethod describes a serialization method of HTTP request's parameters and body.

type Server Uses

type Server struct {
    URL         string                     `json:"url" yaml:"url"`
    Description string                     `json:"description,omitempty" yaml:"description,omitempty"`
    Variables   map[string]*ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"`
}

Server is specified by OpenAPI/Swagger standard version 3.0.

func (Server) MatchRawURL Uses

func (server Server) MatchRawURL(input string) ([]string, string, bool)

func (Server) ParameterNames Uses

func (server Server) ParameterNames() ([]string, error)

func (*Server) Validate Uses

func (server *Server) Validate(c context.Context) (err error)

type ServerVariable Uses

type ServerVariable struct {
    Enum        []interface{} `json:"enum,omitempty" yaml:"enum,omitempty"`
    Default     interface{}   `json:"default,omitempty" yaml:"default,omitempty"`
    Description string        `json:"description,omitempty" yaml:"description,omitempty"`
}

ServerVariable is specified by OpenAPI/Swagger standard version 3.0.

func (*ServerVariable) Validate Uses

func (serverVariable *ServerVariable) Validate(c context.Context) error

type Servers Uses

type Servers []*Server

Servers is specified by OpenAPI/Swagger standard version 3.0.

func (Servers) MatchURL Uses

func (servers Servers) MatchURL(parsedURL *url.URL) (*Server, []string, string)

func (Servers) Validate Uses

func (servers Servers) Validate(c context.Context) error

Validate ensures servers are per the OpenAPIv3 specification.

type SliceUniqueItemsChecker Uses

type SliceUniqueItemsChecker func(items []interface{}) bool

SliceUniqueItemsChecker is an function used to check if an given slice have unique items.

type Swagger Uses

type Swagger struct {
    ExtensionProps
    OpenAPI      string               `json:"openapi" yaml:"openapi"` // Required
    Components   Components           `json:"components,omitempty" yaml:"components,omitempty"`
    Info         *Info                `json:"info" yaml:"info"`   // Required
    Paths        Paths                `json:"paths" yaml:"paths"` // Required
    Security     SecurityRequirements `json:"security,omitempty" yaml:"security,omitempty"`
    Servers      Servers              `json:"servers,omitempty" yaml:"servers,omitempty"`
    Tags         Tags                 `json:"tags,omitempty" yaml:"tags,omitempty"`
    ExternalDocs *ExternalDocs        `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

func (*Swagger) AddOperation Uses

func (swagger *Swagger) AddOperation(path string, method string, operation *Operation)

func (*Swagger) AddServer Uses

func (swagger *Swagger) AddServer(server *Server)

func (*Swagger) MarshalJSON Uses

func (swagger *Swagger) MarshalJSON() ([]byte, error)

func (*Swagger) UnmarshalJSON Uses

func (swagger *Swagger) UnmarshalJSON(data []byte) error

func (*Swagger) Validate Uses

func (swagger *Swagger) Validate(c context.Context) error

type SwaggerLoader Uses

type SwaggerLoader struct {
    IsExternalRefsAllowed  bool
    Context                context.Context
    LoadSwaggerFromURIFunc func(loader *SwaggerLoader, url *url.URL) (*Swagger, error)
    // contains filtered or unexported fields
}

Code:

package main

import (
    "fmt"
    "net"
    "net/http"
    "net/http/httptest"
    "net/url"
    "testing"

    "github.com/stretchr/testify/require"
)

const addr = "localhost:7965"

func TestLoadYAML(t *testing.T) {
    spec := []byte(`
openapi: 3.0.0
info:
  title: An API
  version: v1

components:
  schemas:
    NewItem:
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    ErrorModel:
      type: object
      required: [code, message]
      properties:
        code: {type: integer}
        message: {type: string}

paths:
  /items:
    put:
      description: ''
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewItem'
      responses:
        default: &defaultResponse # a YAML ref
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorModel'
`)

    loader := NewSwaggerLoader()
    doc, err := loader.LoadSwaggerFromData(spec)
    require.NoError(t, err)
    require.Equal(t, "An API", doc.Info.Title)
    require.Equal(t, 2, len(doc.Components.Schemas))
    require.Equal(t, 1, len(doc.Paths))
    def := doc.Paths["/items"].Put.Responses.Default().Value
    desc := "unexpected error"
    require.Equal(t, &desc, def.Description)
    err = doc.Validate(loader.Context)
    require.NoError(t, err)
}

func main() {
    source := `{"info":{"description":"An API"}}`
    swagger, err := NewSwaggerLoader().LoadSwaggerFromData([]byte(source))
    if err != nil {
        panic(err)
    }
    fmt.Print(swagger.Info.Description)
}

func TestResolveSchemaRef(t *testing.T) {
    source := []byte(`{"openapi":"3.0.0","info":{"title":"MyAPI","version":"0.1",description":"An API"},"paths":{},"components":{"schemas":{"B":{"type":"string"},"A":{"allOf":[{"$ref":"#/components/schemas/B"}]}}}}`)
    loader := NewSwaggerLoader()
    doc, err := loader.LoadSwaggerFromData(source)
    require.NoError(t, err)
    err = doc.Validate(loader.Context)

    require.NoError(t, err)
    refAVisited := doc.Components.Schemas["A"].Value.AllOf[0]
    require.Equal(t, "#/components/schemas/B", refAVisited.Ref)
    require.NotNil(t, refAVisited.Value)
}

func TestResolveSchemaRefWithNullSchemaRef(t *testing.T) {
    source := []byte(`{"openapi":"3.0.0","info":{"title":"MyAPI","version":"0.1","description":"An API"},"paths":{"/foo":{"post":{"requestBody":{"content":{"application/json":{"schema":null}}}}}}}`)
    loader := NewSwaggerLoader()
    doc, err := loader.LoadSwaggerFromData(source)
    require.NoError(t, err)
    err = doc.Validate(loader.Context)
    require.EqualError(t, err, `invalid paths: found unresolved ref: ""`)
}

func TestResolveResponseExampleRef(t *testing.T) {
    source := []byte(`
openapi: 3.0.1
info:
  title: My API
  version: 1.0.0
components:
  examples:
    test:
      value:
        error: false
paths:
  /:
    get:
      responses:
        200:
          description: A test response
          content:
            application/json:
              examples:
                test:
                  $ref: '#/components/examples/test'`)
    loader := NewSwaggerLoader()
    doc, err := loader.LoadSwaggerFromData(source)
    require.NoError(t, err)

    err = doc.Validate(loader.Context)
    require.NoError(t, err)

    example := doc.Paths["/"].Get.Responses.Get(200).Value.Content.Get("application/json").Examples["test"]
    require.NotNil(t, example.Value)
    require.Equal(t, example.Value.Value.(map[string]interface{})["error"].(bool), false)
}

type sourceExample struct {
    Location *url.URL
    Spec     []byte
}

type multipleSourceSwaggerLoaderExample struct {
    Sources []*sourceExample
}

func (l *multipleSourceSwaggerLoaderExample) LoadSwaggerFromURI(
    loader *SwaggerLoader,
    location *url.URL,
) (*Swagger, error) {
    source := l.resolveSourceFromURI(location)
    if source == nil {
        return nil, fmt.Errorf("Unsupported URI: '%s'", location.String())
    }
    return loader.LoadSwaggerFromData(source.Spec)
}

func (l *multipleSourceSwaggerLoaderExample) resolveSourceFromURI(location fmt.Stringer) *sourceExample {
    locationString := location.String()
    for _, v := range l.Sources {
        if v.Location.String() == locationString {
            return v
        }
    }
    return nil
}

func TestResolveSchemaExternalRef(t *testing.T) {
    rootLocation := &url.URL{Scheme: "http", Host: "example.com", Path: "spec.json"}
    externalLocation := &url.URL{Scheme: "http", Host: "example.com", Path: "external.json"}
    rootSpec := []byte(fmt.Sprintf(
        `{"openapi":"3.0.0","info":{"title":"MyAPI","version":"0.1","description":"An API"},"paths":{},"components":{"schemas":{"Root":{"allOf":[{"$ref":"%s#/components/schemas/External"}]}}}}`,
        externalLocation.String(),
    ))
    externalSpec := []byte(`{"openapi":"3.0.0","info":{"title":"MyAPI","version":"0.1","description":"External Spec"},"paths":{},"components":{"schemas":{"External":{"type":"string"}}}}`)
    multipleSourceLoader := &multipleSourceSwaggerLoaderExample{
        Sources: []*sourceExample{
            {
                Location: rootLocation,
                Spec:     rootSpec,
            },
            {
                Location: externalLocation,
                Spec:     externalSpec,
            },
        },
    }
    loader := &SwaggerLoader{
        IsExternalRefsAllowed:  true,
        LoadSwaggerFromURIFunc: multipleSourceLoader.LoadSwaggerFromURI,
    }
    doc, err := loader.LoadSwaggerFromURI(rootLocation)
    require.NoError(t, err)
    err = doc.Validate(loader.Context)

    require.NoError(t, err)
    refRootVisited := doc.Components.Schemas["Root"].Value.AllOf[0]
    require.Equal(t, fmt.Sprintf("%s#/components/schemas/External", externalLocation.String()), refRootVisited.Ref)
    require.NotNil(t, refRootVisited.Value)
}

func TestLoadErrorOnRefMisuse(t *testing.T) {
    spec := []byte(`
openapi: '3.0.0'
servers: [{url: /}]
info:
  title: ''
  version: '1'
components:
  schemas:
    Thing: {type: string}
paths:
  /items:
    put:
      description: ''
      requestBody:
        $ref: '#/components/schemas/Thing'
      responses:
        '201':
          description: ''
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Thing'
`)

    loader := NewSwaggerLoader()
    _, err := loader.LoadSwaggerFromData(spec)
    require.Error(t, err)
}

func TestLoadPathParamRef(t *testing.T) {
    spec := []byte(`
openapi: '3.0.0'
info:
  title: ''
  version: '1'
components:
  parameters:
    testParam:
      name: test
      in: query
      schema:
        type: string
paths:
  '/':
    parameters:
      - $ref: '#/components/parameters/testParam'
    get:
      responses:
        '200':
          description: Test call.
`)

    loader := NewSwaggerLoader()
    swagger, err := loader.LoadSwaggerFromData(spec)
    require.NoError(t, err)

    require.NotNil(t, swagger.Paths["/"].Parameters[0].Value)
}

func TestLoadRequestExampleRef(t *testing.T) {
    spec := []byte(`
openapi: '3.0.0'
info:
  title: ''
  version: '1'
components:
  examples:
    test:
      value:
        hello: world
paths:
  '/':
    post:
      requestBody:
        content:
          application/json:
            examples:
              test:
                $ref: "#/components/examples/test"
      responses:
        '200':
          description: Test call.
`)

    loader := NewSwaggerLoader()
    swagger, err := loader.LoadSwaggerFromData(spec)
    require.NoError(t, err)

    require.NotNil(t, swagger.Paths["/"].Post.RequestBody.Value.Content.Get("application/json").Examples["test"])
}

func createTestServer(handler http.Handler) *httptest.Server {
    ts := httptest.NewUnstartedServer(handler)
    l, _ := net.Listen("tcp", addr)
    ts.Listener.Close()
    ts.Listener = l
    return ts
}

func TestLoadFromRemoteURL(t *testing.T) {

    fs := http.FileServer(http.Dir("testdata"))
    ts := createTestServer(fs)
    ts.Start()
    defer ts.Close()

    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    url, err := url.Parse("http://" + addr + "/test.openapi.json")
    require.NoError(t, err)

    swagger, err := loader.LoadSwaggerFromURI(url)
    require.NoError(t, err)

    require.Equal(t, "string", swagger.Components.Schemas["TestSchema"].Value.Type)
}

func TestLoadFileWithExternalSchemaRef(t *testing.T) {
    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    swagger, err := loader.LoadSwaggerFromFile("testdata/testref.openapi.json")
    require.NoError(t, err)

    require.NotNil(t, swagger.Components.Schemas["AnotherTestSchema"].Value.Type)
}

func TestLoadFileWithExternalSchemaRefSingleComponent(t *testing.T) {
    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    swagger, err := loader.LoadSwaggerFromFile("testdata/testrefsinglecomponent.openapi.json")
    require.NoError(t, err)

    require.NotNil(t, swagger.Components.Responses["SomeResponse"])
    desc := "this is a single response definition"
    require.Equal(t, &desc, swagger.Components.Responses["SomeResponse"].Value.Description)
}

func TestLoadRequestResponseHeaderRef(t *testing.T) {
    spec := []byte(`
{
    "openapi": "3.0.0",
    "info": {
        "title": "",
        "version": "1"
    },
    "paths": {
      "/test": {
        "post": {
          "responses": {
            "default": {
              "description": "test",
              "headers": {
                "X-TEST-HEADER": {
                  "$ref": "#/components/headers/TestHeader"
                }
              }
            }
          }
        }
      }
    },
    "components": {
      "headers": {
        "TestHeader": {
          "description": "testheader"
        }
      }
    }
}`)

    loader := NewSwaggerLoader()
    swagger, err := loader.LoadSwaggerFromData(spec)
    require.NoError(t, err)

    require.NotNil(t, swagger.Paths["/test"].Post.Responses["default"].Value.Headers["X-TEST-HEADER"].Value.Description)
    require.Equal(t, "testheader", swagger.Paths["/test"].Post.Responses["default"].Value.Headers["X-TEST-HEADER"].Value.Description)
}

func TestLoadFromDataWithExternalRequestResponseHeaderRemoteRef(t *testing.T) {
    spec := []byte(`
{
    "openapi": "3.0.0",
    "info": {
        "title": "",
        "version": "1"
    },
    "paths": {
        "/test": {
            "post": {
                "responses": {
                    "default": {
                        "description": "test",
                        "headers": {
                            "X-TEST-HEADER": {
                                "$ref": "http://` + addr + `/components.openapi.json#/components/headers/CustomTestHeader"
                            }
                        }
                    }
                }
            }
        }
    }
}`)

    fs := http.FileServer(http.Dir("testdata"))
    ts := createTestServer(fs)
    ts.Start()
    defer ts.Close()

    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    swagger, err := loader.LoadSwaggerFromDataWithPath(spec, &url.URL{Path: "testdata/testfilename.openapi.json"})
    require.NoError(t, err)

    require.NotNil(t, swagger.Paths["/test"].Post.Responses["default"].Value.Headers["X-TEST-HEADER"].Value.Description)
    require.Equal(t, "description", swagger.Paths["/test"].Post.Responses["default"].Value.Headers["X-TEST-HEADER"].Value.Description)
}

func TestLoadYamlFile(t *testing.T) {
    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    swagger, err := loader.LoadSwaggerFromFile("testdata/test.openapi.yml")
    require.NoError(t, err)

    require.Equal(t, "OAI Specification in YAML", swagger.Info.Title)
}

func TestLoadYamlFileWithExternalSchemaRef(t *testing.T) {
    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    swagger, err := loader.LoadSwaggerFromFile("testdata/testref.openapi.yml")
    require.NoError(t, err)

    require.NotNil(t, swagger.Components.Schemas["AnotherTestSchema"].Value.Type)
}

func TestLoadYamlFileWithExternalPathRef(t *testing.T) {
    loader := NewSwaggerLoader()
    loader.IsExternalRefsAllowed = true
    swagger, err := loader.LoadSwaggerFromFile("testdata/pathref.openapi.yml")
    require.NoError(t, err)

    require.NotNil(t, swagger.Paths["/test"].Get.Responses["200"].Value.Content["application/json"].Schema.Value.Type)
    require.Equal(t, "string", swagger.Paths["/test"].Get.Responses["200"].Value.Content["application/json"].Schema.Value.Type)
}

func TestResolveResponseLinkRef(t *testing.T) {
    source := []byte(`
openapi: 3.0.1
info:
  title: My API
  version: 1.0.0
components:
  links:
    Father:
        description: link to to the father
        operationId: getUserById
        parameters:
          "id": "$response.body#/fatherId"
paths:
  /users/{id}:
    get:
      operationId: getUserById,
      parameters:
        - name: id,
          in: path
          schema:
            type: string
      responses:
        200:
          description: A test response
          content:
            application/json:
          links:
            father:
              $ref: '#/components/links/Father'
`)
    loader := NewSwaggerLoader()
    doc, err := loader.LoadSwaggerFromData(source)
    require.NoError(t, err)

    err = doc.Validate(loader.Context)
    require.NoError(t, err)

    response := doc.Paths[`/users/{id}`].Get.Responses.Get(200).Value
    link := response.Links[`father`].Value
    require.NotNil(t, link)
    require.Equal(t, "getUserById", link.OperationID)
    require.Equal(t, "link to to the father", link.Description)
}

func TestResolveNonComponentsRef(t *testing.T) {
    spec := []byte(`
openapi: 3.0.0
info:
  title: An API
  version: v1

components:
  schemas:
    NewItem:
      required: [name]
      properties:
        name: {type: string}
        tag: {type: string}
    ErrorModel:
      type: object
      required: [code, message]
      properties:
        code: {type: integer}
        message: {type: string}

paths:
  /items:
    put:
      description: ''
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewItem'
      responses:
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorModel'
    post:
      description: ''
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/paths/~1items/put/requestBody/content/application~1json/schema'
      responses:
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorModel'
`)

    loader := NewSwaggerLoader()
    doc, err := loader.LoadSwaggerFromData(spec)
    require.NoError(t, err)
    err = doc.Validate(loader.Context)
    require.NoError(t, err)
}

func NewSwaggerLoader Uses

func NewSwaggerLoader() *SwaggerLoader

func (*SwaggerLoader) LoadSwaggerFromData Uses

func (swaggerLoader *SwaggerLoader) LoadSwaggerFromData(data []byte) (*Swagger, error)

func (*SwaggerLoader) LoadSwaggerFromDataWithPath Uses

func (swaggerLoader *SwaggerLoader) LoadSwaggerFromDataWithPath(data []byte, path *url.URL) (*Swagger, error)

LoadSwaggerFromDataWithPath takes the OpenApi spec data in bytes and a path where the resolver can find referred elements and returns a *Swagger with all resolved data or an error if unable to load data or resolve refs.

func (*SwaggerLoader) LoadSwaggerFromFile Uses

func (swaggerLoader *SwaggerLoader) LoadSwaggerFromFile(path string) (*Swagger, error)

func (*SwaggerLoader) LoadSwaggerFromURI Uses

func (swaggerLoader *SwaggerLoader) LoadSwaggerFromURI(location *url.URL) (*Swagger, error)

func (*SwaggerLoader) ResolveRefsIn Uses

func (swaggerLoader *SwaggerLoader) ResolveRefsIn(swagger *Swagger, path *url.URL) (err error)

type Tag Uses

type Tag struct {
    Name         string        `json:"name,omitempty" yaml:"name,omitempty"`
    Description  string        `json:"description,omitempty" yaml:"description,omitempty"`
    ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

Tag is specified by OpenAPI/Swagger 3.0 standard.

type Tags Uses

type Tags []*Tag

Tags is specified by OpenAPI/Swagger 3.0 standard.

func (Tags) Get Uses

func (tags Tags) Get(name string) *Tag

Package openapi3 imports 19 packages (graph) and is imported by 83 packages. Updated 2020-11-22. Refresh now. Tools for package owners.