openapi3edit

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2022 License: MIT Imports: 15 Imported by: 0

README

Spectrum OpenAPI 3 Inspect, Modify & Compare

Docs

Spectrum openapi3edit is a library to assist in inspecting and modifying OpenAPI specs.

OpenAPI specifications can be large and have many endpoints which can make it difficult to manage. Additionally, some services may consist of many specs created by different people, teams and software, so some ability to make various specs consistent is desirable, especially when the individual specs need to be merged into a master spec.

Key Features include:

  • Inspect: Various functions to examine aspects of a OpenAPI 3 spec including OperationIDs, paths, endpoint, schemas, tags, etc.
  • Modify: Ability to modify various properties programmatically.
  • Intersection: Ability to compare two specs and show the overlap.

Usage

Steps for clean merging of multiple specs.

  1. Examine all specs for consistent operationIds and tags
  2. Ensure that all specs can be merged to common server base URL and paths
  3. Optionally delete endpoint security from each spec and add it to merged spec
  4. Check / deletee overlapping operationIDs, endpoints (method+path) and schema components
  5. Validate resulting spec
Inspect & Modify

Use SpecMoreModifyMulti and SpecMoreModifyMultiOpts to handle to inspect and modify mulitple files.

Compare

Use openapi3edit.SpecsIntersection()

// spec1 and spec2 are *github.com/getkin/kin-openapi/openapi3.Swagger
intersectionData := openapi3edit.SpecsIntersection(spec1, spec2)
intersectionData.Sort()
Delete

After running intersection, you can use the resulting data to delete those items from a spec using SpecDeleteProperties. Be sure to validate afterwards.

This is useful when merging to specs with an overlap. To check for cleanliness of merging, you can:

  1. run an intersection
  2. delete the intersection from one of the sepcs and ensures it still validates
  3. merge the specs

Examples

Add Bearer Token Auth
openapi3edit.SecuritySchemeAddBearertoken(
    spec, "", "",
    []string{},
    []string{
        "Authentication",
    },
)

Documentation

Index

Constants

View Source
const (
	SecuritySchemeApikeyDefaultName      = "ApiKeyAuth"
	SecuritySchemeBearertokenDefaultName = "BearerAuth"
	SchemeHTTP                           = "http"
	TokenTypeBearer                      = "bearer"
)

Variables

This section is empty.

Functions

func FixFile

func FixFile(input, output string, prefix, indent string, validateOutput bool) (*openapi3.Spec, []*openapi3.OperationMeta, error)

func MapSliceIntersectionExists

func MapSliceIntersectionExists(haystack map[string]int, needles []string) bool

func MoveRequestBodies

func MoveRequestBodies(spec *openapi3.Spec, move bool) ([]*openapi3.OperationMeta, error)

MoveRequestBodies moves `requestBody` `$ref` to the operation which appears to be supported by more tools.

func NullToEmpty

func NullToEmpty(spec *openapi3.Spec)

func NullToEmptyPaths

func NullToEmptyPaths(spec *openapi3.Spec)

NullToEmptyPaths converts a `path` property from `null` to an empty set `{}` to satisfy OpenAPI Generator which will fail on the following error "-attribute paths is not of type `object`"

func ParsePathParametersParens

func ParsePathParametersParens(urlPath string) []string

func PathItemHasEndpoints

func PathItemHasEndpoints(pathItem *oas3.PathItem) bool

func PathMatchGeneric

func PathMatchGeneric(path1, path2 string) bool

func PathMethods

func PathMethods(pathItem *oas3.PathItem) []string

func PathVarsToGeneric

func PathVarsToGeneric(input string) string

func RemoveOperationsSecurity

func RemoveOperationsSecurity(spec *openapi3.Spec)

RemoveOperationsSecurity removes the security property for all operations. It is useful when building a spec to get individual specs to validate before setting the correct security property.

func SecuritySchemeAddBearertoken

func SecuritySchemeAddBearertoken(spec *openapi3.Spec, schemeName, bearerFormat string, inclTags, skipTags []string)

SecuritySchemeAddBearertoken adds bearer token auth to spec and operations.

func SecuritySchemeAddOperation

func SecuritySchemeAddOperation(op *oas3.Operation, schemeName string, schemeValue []string)

SecuritySchemeAddOperation adds a scheme name and value to an operation.

func SecuritySchemeApikeyAddDefinition

func SecuritySchemeApikeyAddDefinition(spec *openapi3.Spec, schemeName, location, name string) error

AddAPIKey adds an API Key definition to the spec. https://swagger.io/docs/specification/authentication/api-keys/

func SecuritySchemeApikeyAddOperations

func SecuritySchemeApikeyAddOperations(spec *openapi3.Spec, tags []string, keyName string)

func SecuritySchemeBearertokenAddDefinition

func SecuritySchemeBearertokenAddDefinition(spec *openapi3.Spec, schemeName, bearerFormat string)

func SecuritySchemeBearertokenAddOperationsByTags

func SecuritySchemeBearertokenAddOperationsByTags(spec *openapi3.Spec, schemeName string, inclTags, skipTags []string)

func SortParameters

func SortParameters(sourceParams oas3.Parameters, sortOrder []string) oas3.Parameters
func OperationHasParameter(paramNameWant string, op *oas3.Operation) bool {
	paramNameWantLc := strings.ToLower(strings.TrimSpace(paramNameWant))
	for _, paramRef := range op.Parameters {
		if paramRef.Value == nil {
			continue
		}
		param := paramRef.Value
		param.Name = strings.TrimSpace(param.Name)
		paramNameTryLc := strings.ToLower(param.Name)
		if paramNameWantLc == paramNameTryLc {
			return true
		}
	}
	return false
}

SortParameters sorts parameters according to an input name list. This used to resort parameters inline with path path parameters so they line up properly when rendered.

func SpecAddCustomProperties

func SpecAddCustomProperties(spec *openapi3.Spec, custom map[string]interface{}, addToOperations, addToSchemas bool)

func SpecAddOperationMetas

func SpecAddOperationMetas(spec *openapi3.Spec, metas map[string]openapi3.OperationMeta, overwrite bool)

func SpecDeleteOperations

func SpecDeleteOperations(spec *openapi3.Spec, delThis func(urlpath, method string, op *oas3.Operation) bool)

func SpecDeleteProperties

func SpecDeleteProperties(spec *openapi3.Spec, md SpecMetadata)

func SpecEndpoints

func SpecEndpoints(spec *openapi3.Spec, generic bool) []string

func SpecMoreModifyMulti

func SpecMoreModifyMulti(sm *openapi3.SpecMore, opts SpecMoreModifyMultiOpts) error

SpecMoreModifyMulti is used to perform multiple updates on an OpenAPI 3 spec.

func SpecOperationIds

func SpecOperationIds(spec *openapi3.Spec) map[string]int

func SpecOperationIdsFromSummaries

func SpecOperationIdsFromSummaries(spec *openapi3.Spec, errorOnEmpty bool) error

func SpecOperationsCount

func SpecOperationsCount(spec *openapi3.Spec) uint

func SpecOperationsFixResponseReferences

func SpecOperationsFixResponseReferences(spec *openapi3.Spec) []*openapi3.OperationMeta

func SpecOperationsSetDeprecated

func SpecOperationsSetDeprecated(spec *openapi3.Spec, newDeprecated bool)

func SpecPathsModify

func SpecPathsModify(spec *openapi3.Spec, opts SpecPathsModifyOpts) error

func SpecSchemasSetDeprecated

func SpecSchemasSetDeprecated(spec *openapi3.Spec, newDeprecated bool)

func SpecSetDeprecatedImplicit

func SpecSetDeprecatedImplicit(spec *openapi3.Spec)

func SpecSetOperation

func SpecSetOperation(spec *openapi3.Spec, path, method string, op oas3.Operation) error

SpecSetOperation sets an operation in a OpenAPI Specification.

func SpecSetSchemaPropertiesOptional

func SpecSetSchemaPropertiesOptional(spec *openapi3.Spec, rxOptional *regexp.Regexp)

func SpecTagsCondense

func SpecTagsCondense(spec *openapi3.Spec)

SpecTagsCondense removes unused tags from the top level specification by comparing with tags used in operations.

func SpecTagsModify

func SpecTagsModify(spec *openapi3.Spec, changeTagsRaw map[string]string)

func SpecTagsOrder

func SpecTagsOrder(spec *openapi3.Spec, explicitSortedTagNames []string) error

SpecTagsOrder sorts a specs tags based on an input set and explitcit sort order. The remaining tags are sorted alphabetically.

func TagsOrder

func TagsOrder(curTags oas3.Tags, explicitSortedTagNames []string) (oas3.Tags, error)

TagsOrder creates a list of ordered tags based on an input set and explitcit sort order. The remaining tags are sorted alphabetically.

func ValidateFixOperationPathParameters

func ValidateFixOperationPathParameters(spec *openapi3.Spec, fix bool) ([]*openapi3.OperationMeta, error)

ValidateFixOperationPathParameters will add missing path parameters and re-sort parameters so required path parameters are on top and sorted by their position in the path.

func ValidateFixOperationResponseTypes

func ValidateFixOperationResponseTypes(spec *openapi3.Spec, fix bool) ([]*openapi3.OperationMeta, error)

ValidateFixOperationResponseTypes looks for `application/json` responses with response schema types that are not `array` or `object`. If the responses is a string or integer, it will reset the response mime type to `text/plain`.

Types

type Endpoint

type Endpoint struct {
	Path      string
	Method    string
	Operation *oas3.Operation
}

func PathEndpoints

func PathEndpoints(url string, pathItem *oas3.PathItem) []Endpoint

func (*Endpoint) String

func (ep *Endpoint) String() string

type IntersectionData

type IntersectionData struct {
	Spec1        SpecMetadata
	Spec2        SpecMetadata
	Intersection SpecMetadata
}

func NewIntersectionData

func NewIntersectionData() IntersectionData

func SpecsIntersection

func SpecsIntersection(spec1, spec2 *openapi3.Spec) IntersectionData

func (*IntersectionData) Sort

func (idata *IntersectionData) Sort()

type OperationMore

type OperationMore struct {
	Path      string
	Method    string
	Operation *oas3.Operation
}

OperationMore is used for two purposes: (a) to store path and method information with the operation and (b) to provide a container to organize operation related functions.

func (*OperationMore) AddExternalDocs

func (opm *OperationMore) AddExternalDocs(docURL, docDescription string, preserveIfReqEmpty bool) error

func (*OperationMore) AddRequestBodySchemaRef

func (opm *OperationMore) AddRequestBodySchemaRef(description string, required bool, contentType string, schemaRef *oas3.SchemaRef) error

func (*OperationMore) AddResponseBodySchemaRef

func (opm *OperationMore) AddResponseBodySchemaRef(statusCode, description, contentType string, schemaRef *oas3.SchemaRef) error

func (*OperationMore) HasParameter

func (opm *OperationMore) HasParameter(paramNameWant string) bool

type OperationMoreSet

type OperationMoreSet struct {
	OperationMores []OperationMore
}

func QueryOperationsByTags

func QueryOperationsByTags(spec *openapi3.Spec, tags []string) *OperationMoreSet

type PathMeta

type PathMeta struct {
	Current string
	New     string
}

type SpecMetadata

type SpecMetadata struct {
	Endpoints    []string
	OperationIDs []string
	SchemaNames  []string
}

func NewSpecMetadata

func NewSpecMetadata(spec *openapi3.Spec) SpecMetadata

func (*SpecMetadata) Intersection

func (md *SpecMetadata) Intersection(md2 SpecMetadata) SpecMetadata

func (*SpecMetadata) IsEmpty

func (md *SpecMetadata) IsEmpty() bool

func (*SpecMetadata) Sort

func (md *SpecMetadata) Sort()

type SpecMoreModifyMultiOpts

type SpecMoreModifyMultiOpts struct {
	OperationsDeleteFunc     func(urlpath, method string, op *oas3.Operation) bool
	OperationsRenameIdsFunc  func(string, string, *oas3.Operation)
	OperationsRemoveSecurity bool
	OperationsShowIds        bool
	OperationsExec           bool
	Paths                    SpecPathsModifyOpts
	PathsShow                bool
	PathsExec                bool
	TagsOperationFunc        func(string, string, *oas3.Operation)
	Tags                     map[string]string
	TagsShow                 bool
	TagsExec                 bool
}

type SpecPaths

type SpecPaths struct {
	Servers oas3.Servers
	Paths   []PathMeta
}

func InspectPaths

func InspectPaths(spec *openapi3.Spec) SpecPaths

type SpecPathsModifyOpts

type SpecPathsModifyOpts struct {
	ServerPathExec          bool
	ServerPathNew           string
	OpPathRenameNewBase     string
	OpPathRenameNewBaseExec bool
	OpPathRenameFunc        func(string) string
	OpPathRenameFuncExec    bool
}

type UpdateTagsOpts

type UpdateTagsOpts struct {
	TagURLsMap   map[string][]string
	TagsMap      map[string]string
	TagGroupsSet openapi3.TagGroupSet
}

func (*UpdateTagsOpts) ModifyTagsOperationFunc

func (uto *UpdateTagsOpts) ModifyTagsOperationFunc(path, method string, op *oas3.Operation)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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