Categorygithub.com/chanced/openapi
modulepackage
0.2.4
Repository: https://github.com/chanced/openapi.git
Documentation: pkg.go.dev

# README

openapi - An OpenAPI 3.x library for go

Go Reference Latest Version Build Status

openapi is a library for parsing and validating OpenAPI 3.1, 3.0. The intent of the library is to offer building blocks for code and documentation generation.

:warning: This library is under active development; there may be breaking changes and bugs.

Features

  • $ref resolution
  • All keys retain their order from the markup using slices of key/values which aids in code generation.
  • Validation (see the validation section)
  • All non-primitive nodes have an absolute & relative location
  • Strings are text.Text which has case conversions and strings functions as methods.
  • Extensions, unknown JSON Schema keywords, examples, and a few other fields are instances of jsonx.RawMessage which comes with a few helper methods.
  • Supports both JSON and YAML

Usage

package main

import (
    "github.com/chanced/openapi"
    "github.com/chanced/uri"
    "github.com/santhosh-tekuri/jsonschema/v5"
    "embed"
    "io"
    "path/filepath"
    "log"
)

//go:embed spec
var specFiles embed.FS

func main() {
    ctx := context.Background()

    c, err := openapi.SetupCompiler(jsonschema.NewCompiler()) // adding schema files
    if err != nil {
        log.Fatal(err)
    }
    v, err := openapi.NewValidator(c)
    if err != nil {
        log.Fatal(err)
    }

    fn := func(_ context.Context, uri uri.URI, kind openapi.Kind) (openapi.Kind, []byte, error){
        f, err := specFiles.Open(fp)
        if err != nil {
            log.Fatal(err)
        }
        // you can return either JSON or YAML
        d, err := io.ReadAll(f)
        if err != nil{
            log.fatal(err)
        }
        // use the uri or the data to determine the Kind
        return openapi.KindDocument, d, nil
    }
    // you can Load either JSON or YAML
    // Load validates the Document as well.
    doc, err := openapi.Load(ctx, "spec/openapi.yaml", v, fn)
    if err != nil{
        log.Fatal(err)
    }
    _ = doc // *openapi.Document
}

Validation

The standard validator (StdValidator) currently validates OpenAPI documents with JSON Schema. Per OpenAPI's documentation, this may not be enough to properly encapsulate all the nuances of a specification. However, JSON Schema is able to successfully validate the current OpenAPI 3.1 Specification test suite.

Validation is an area that still needs work. If you do find cases where the current validator is not sufficient, please open an issue so that the library can be updated with proper coverage of that case.

Dependencies

DependencyUsage
github.com/santhosh-tekuri/jsonschema/v5used in the StdValidator to validate OpenAPI documents & components
github.com/chanced/caps/textused for all string fields to provide case conversion and functions from strings as methods
github.com/chanced/jsonpointerrelative locations of all non-scalar nodes
github.com/tidwall/gjsonJSON parsing
github.com/chanced/jsonxraw JSON type and a toolkit for json type detection & parsing
github.com/chanced/mapssmall utility used to sort Extensions
github.com/chanced/transcodeused to transform YAML into JSON and vice versa
github.com/chanced/uriused to represent URIs
github.com/Masterminds/semveropenapi field and version detection of OpenAPI documents
gopkg.in/yaml.v3needed to satisfy yaml.Marshaler and yaml.Unmarshaler
github.com/google/go-cmptesting purposes

Contributions

Please feel free to open up an issue or create a pull request if you find issues or if there are features you'd like to see added.

License

MIT

# Functions

CompileSchemas compiles the OpenAPI and JSON Schema resources using compiler.
IsExtensionKey returns true if the key starts with "x-".
IsRef returns true for the following types: - *Reference - *SchemaRef - *OperationRef.
Load loads an OpenAPI document from a URI and validate it with the provided validator.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Each fs.FS in resources will be walked and all files ending in .json will be be added to the compiler.
SetupCompiler adds OpenAPI and JSON Schema resources to a Compiler.
TryGetOpenAPIVersion attempts to extract the OpenAPI version from raw JSON data and parse it as a semver.Version.
TryGetSchemaDialect attempts to extract the schema dialect from raw JSON data.

# Constants

$dynamicAnchor.
$recursiveAnchor.
$anchor.
No description provided by the author
InCookie - Used to pass a specific cookie value to the API.
InHeader - Custom headers that are expected as part of the request.
InPath - Used together with Path Templating, where the parameter value is actually part of the operation's URL.
InQuery - Parameters that are appended to the URL.
URI for JSON Schema 2019-09.
URI for JSON Schema 2020-12.
*Callbacks.
*Component[*Callbacks].
*CallbacksMap.
*Components.
*Contact.
*Discriminator.
*Document.
*Encoding.
*EncodingMap.
*Example.
*Component[*Example].
*ExampleMap.
*ExternalDocs.
*Header.
*Component[*Header].
*HeaderMap.
*HeaderSlice.
*Info.
*License.
*Link.
*Component[*Link].
*LinkMap.
*MediaType.
*MediaTypeMap.
*OAuthFlow.
*OAuthFlows.
*Operation.
*OperationRef.
*Parameter.
*Component[*Parameter].
*ParameterMap.
*ParameterSlice.
*PathItem.
*Component[*PathItem].
*PathItemMap.
*Paths.
*Reference.
*RequestBody.
*Component[*RequestBody].
*RequestBodyMap.
*Response.
*Component[*Response].
*ResponseMap.
*Schema.
*SchemaMap.
*SchemaRef.
*SchemaSlice.
*Scope.
*Scopes.
*SecurityRequirement.
*SecurityRequirementItem.
*SecurityRequirements.
*SecurityScheme.
*Component[*SecurityScheme].
*SecuritySchemeMap.
*Server.
*Component[*Server].
*ServerSlice.
*ServerVariable.
*ServerVariableMap.
*Tag.
*TagSlice.
No description provided by the author
*XML.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
URI for OpenAPI 3.0 schema.
URI for OpenAPI 3.1 schema.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
SecuritySchemeTypeAPIKey = "apiKey".
SecuritySchemeTypeHTTP = "http".
SecuritySchemeTypeMutualTLS = mutualTLS.
SecuritySchemeTypeOAuth2 = oauth2.
SecuritySchemeTypeOpenIDConnect = "openIdConnect".
StyleDeepObject a simple way of rendering nested objects using form parameters (applies to objects only).
StyleForm for.
StyleLabel dot-prefixed values, also known as label expansion.
StyleMatrix is semicolon-prefixed values, also known as path-style expansion.
StylePipeDelimited is pipeline-separated array values.
StyleSimple comma-separated values.
TypeArray = array https://json-schema.org/understanding-json-schema/reference/array.html#array.
TypeBoolean = boolean https://json-schema.org/understanding-json-schema/reference/boolean.html#boolean.
TypeInteger = integer https://json-schema.org/understanding-json-schema/reference/numeric.html#integer.
TypeNull = null https://json-schema.org/understanding-json-schema/reference/null.html#null.
TypeNumber = number https://json-schema.org/understanding-json-schema/reference/numeric.html#number.
TypeObject = object https://json-schema.org/understanding-json-schema/reference/object.html#object.
TypeString = string https://json-schema.org/understanding-json-schema/reference/string.html#string.

# Variables

No description provided by the author
No description provided by the author
ErrInvalidSemVer is returned a version is found to be invalid when being parsed.
ErrInvalidMetadata is returned when the metadata of a semver is an invalid format.
ErrInvalidPrerelease is returned when the pre-release of a semver is an invalid format.
No description provided by the author
No description provided by the author
ErrNotReference indicates not a reference.
No description provided by the author
JSONSchemaDialect201909 is the URI for JSON Schema 2019-09.
JSONSchema202012SchemaURI is the URI for JSON Schema 2020-12.
OpenAPI30Schema is the URI for the JSON Schema of OpenAPI 3.0.
OpenAPI31Schema is the URI for the JSON Schema of OpenAPI 3.1.
SupportedVersions is a semantic versioning constraint for versions supported by openapi This is currently: >= 3.0.0, < 3.2.0.
Version3_0 is a semantic version for 3.0.x.
Version3_1 is a semantic version for 3.1.x.
VersionConstraints3_0 is a semantic versioning constraint for 3.0: >= 3.0.0, < 3.1.0.
SemanticVersion3_0 is a semantic versioning constraint for 3.1: >= 3.1.0, < 3.2.0.

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
Callbacks is map of possible out-of band callbacks related to the parent operation.
CompiledSchemas are used in the the StdValidator.
No description provided by the author
ComponentEntry is an entry in a ComponentMap consisting of a Key/Value pair for an object consiting of Component[T]s.
ComponentMap is a pseudo map consisting of Components with type T.
Components holds a set of reusable objects for different aspects of the OAS.
ComponentSlice is a slice of Components of type T.
Contact information for the exposed API.
Discriminator can be used to aid in serialization, deserialization, and validation of request bodies or response payloads which may be one of a number of different schemas.
Document root object of the Document document.
No description provided by the author
Encoding definition applied to a single schema property.
No description provided by the author
Example is an example for various api interactions such as Responses In all cases, the example value is expected to be compatible with the type schema of its associated value.
ExternalDocs allows referencing an external resource for extended documentation.
Header follows the structure of the Parameter Object with the following changes: - name MUST NOT be specified, it is given in the corresponding headers map.
Info provides metadata about the API.
No description provided by the author
No description provided by the author
No description provided by the author
License information for the exposed API.
Link represents a possible design-time link for a response.
No description provided by the author
No description provided by the author
No description provided by the author
MediaType provides schema and examples for the media type identified by its key.
OAuthFlow configuration details for a supported OAuth Flow.
OAuthFlows allows configuration of the supported OAuth Flows.
ObjMap is a map of OpenAPI Objects of type T.
No description provided by the author
Operation describes a single API operation on a path.
No description provided by the author
Parameter describes a single operation parameter.
PathItem describes the operations available on a single path.
No description provided by the author
Paths holds the relative paths to the individual endpoints and their operations.
Reference is simple object to allow referencing other components in the OpenAPI document, internally and externally.
Regexp is a wrapper around *regexp.Regexp to allow for marshinaling/unmarshaling.
RequestBody describes a single request body.
No description provided by the author
Response describes a single response from an API Operation, including design-time, static links to operations based on the response.
Schema allows the definition of input and output data types.
No description provided by the author
SchemaMap is a pseudo, ordered map ofASew3 Schemas Under the hood, SchemaMap is a slice of SchemaEntry.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
SecurityScheme defines a security scheme that can be used by the operations.
No description provided by the author
Server representation of a Server.
ServerVariable for server URL template substitution.
StdValidator is an implemtation of the Validator interface.
Tag adds metadata that is used by the Operation Object.
No description provided by the author
No description provided by the author
No description provided by the author
XML is a metadata object that allows for more fine-tuned XML model definitions.

# Interfaces

CompiledSchema is an interface satisfied by a JSON Schema implementation that validates primitive interface{} types.
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
Extensions for OpenAPI While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Type restricts to a JSON Schema specific type https://json-schema.org/understanding-json-schema/reference/type.html#type.
Types is a set of Types.