openapi3edit

package
v1.16.11 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2023 License: MIT Imports: 25 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 (
	ErrMsgSchemaKeyCollision    = "schemaKeySollision"
	ErrMsgOperationMissingID    = "operationMissingID"
	ErrMsgOperationRequestCTGT1 = "operationRequestContentTypeGT1"
)
View Source
const (
	SecuritySchemeApikeyDefaultName      = "ApiKeyAuth" // #nosec G101
	SecuritySchemeBearertokenDefaultName = "BearerAuth"
	SchemeHTTP                           = "http"
	TokenTypeBearer                      = "bearer"
)

Variables

View Source
var ErrEmptySchemaName = errors.New("empty schema name encountered")

Functions

func FixFile

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

func FuncSchemaRefModFromSchemaKeyMod added in v1.16.0

func FuncSchemaRefModFromSchemaKeyMod(xf func(string) string) func(string) string

FuncSchemaRefModFromSchemaKeyMod takles a function for modifying schema keys and turns it into a function for modifying JSON schema pointers for schemas keys.

func NewTagsSimple added in v1.13.0

func NewTagsSimple(tagNames []string) oas3.Tags

NewTagsSimple returns a `Tags` struct that can be assigned to `openapi3.Spec.Tags`.

func PathTemplateParamMod added in v1.16.0

func PathTemplateParamMod(p string, xf func(string) string) string

PathTemplateParamMod takes a URL path with templated parameters like `{pet_id}`.`

func SchemaRefModifyRefs added in v1.13.0

func SchemaRefModifyRefs(schRef *oas3.SchemaRef, xf func(string) string)

func SchemaRefModifyRefsRx added in v1.16.0

func SchemaRefModifyRefsRx(schRef *oas3.SchemaRef, rx *regexp.Regexp, repl string)

SchemaRefModifyRefsRx modifies Schema reference schema pointers that match the supplied `*regexp.Regexp` with the replacement string. It was originally designed to convert `#schemas/` to `#components/schemas/`.

func SortParameters

func SortParameters(sourceParams oas3.Parameters, sortOrder []string) oas3.Parameters

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 SpecMoreModifyMulti

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

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

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.

Types

type OperationEdit added in v1.14.0

type OperationEdit struct {
	openapi3.OperationMore
}

OperationEdit 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 NewOperationEdit added in v1.14.0

func NewOperationEdit(opPath, opMethod string, op *oas3.Operation) OperationEdit

func (*OperationEdit) AddSecurityRequirement added in v1.14.0

func (ope *OperationEdit) AddSecurityRequirement(schemeName string, schemeValue []string) error

AddSecurityRequirement adds a scheme name and value to an operation.

func (*OperationEdit) AddToSpec added in v1.14.0

func (ope *OperationEdit) AddToSpec(spec *openapi3.Spec, force bool) (bool, error)

func (*OperationEdit) SetExternalDocs added in v1.14.0

func (ope *OperationEdit) SetExternalDocs(docURL, docDescription string, preserveIfReqEmpty bool) error

func (*OperationEdit) SetRequestBodyAttrs added in v1.14.0

func (ope *OperationEdit) SetRequestBodyAttrs(description string, required bool) error

func (*OperationEdit) SetRequestBodySchemaRef added in v1.14.0

func (ope *OperationEdit) SetRequestBodySchemaRef(mediaType string, schemaRef *oas3.SchemaRef) error

func (*OperationEdit) SetResponseBodySchemaRefMore added in v1.14.0

func (ope *OperationEdit) SetResponseBodySchemaRefMore(statusCode, description, contentType string, schemaRef *oas3.SchemaRef) error

type PathMeta

type PathMeta struct {
	Current string
	New     string
}

type SpecEdit added in v1.14.0

type SpecEdit struct {
	SpecMore openapi3.SpecMore
}

func NewSpecEdit added in v1.16.0

func NewSpecEdit(spec *openapi3.Spec) SpecEdit

func (*SpecEdit) AddCustomProperties added in v1.16.0

func (se *SpecEdit) AddCustomProperties(custom map[string]interface{}, addToOperations, addToSchemas bool)

func (*SpecEdit) AddOperationMetas added in v1.16.0

func (se *SpecEdit) AddOperationMetas(metas map[string]openapi3.OperationMeta, overwrite bool)

func (*SpecEdit) AddSchemaDir added in v1.16.0

func (se *SpecEdit) AddSchemaDir(dir string, fileRx *regexp.Regexp) error

func (*SpecEdit) DeleteOperations added in v1.16.0

func (se *SpecEdit) DeleteOperations(delThis func(urlpath, method string, op *oas3.Operation) bool)

func (*SpecEdit) DeleteProperties added in v1.16.0

func (se *SpecEdit) DeleteProperties(md openapi3.SpecMetadata)

func (*SpecEdit) ExtensionSet added in v1.14.0

func (se *SpecEdit) ExtensionSet(key string, val any)

func (*SpecEdit) OperationIDsFromSummaries added in v1.16.0

func (se *SpecEdit) OperationIDsFromSummaries(errorOnEmpty bool) error

func (*SpecEdit) OperationsFixResponseReferences added in v1.16.1

func (se *SpecEdit) OperationsFixResponseReferences() []*openapi3.OperationMeta

func (*SpecEdit) OperationsOperationIDSummaryReplace added in v1.16.0

func (se *SpecEdit) OperationsOperationIDSummaryReplace(customMapPathMethodToSummary map[string]string, opIDFunc func(s string) string, forceOpID, forceSummary bool)

OperationsOperationIDSummaryReplace sets the OperationID and Summary with a `map[string]string` where the keys are pathMethod values and the values are Summary strings. This currently converts a Summary into an OperationID by using the supplied `opIDFunc`.

func (*SpecEdit) OperationsRequestBodyFlattenSchemas added in v1.16.1

func (se *SpecEdit) OperationsRequestBodyFlattenSchemas(schemaKeySuffix string) error

func (*SpecEdit) OperationsRequestBodyMove added in v1.16.1

func (se *SpecEdit) OperationsRequestBodyMove(move bool) ([]*openapi3.OperationMeta, error)

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

func (*SpecEdit) OperationsSecurityRemove added in v1.16.1

func (se *SpecEdit) OperationsSecurityRemove(inclPathMethods []string) error

OperationsRemoveSecurity 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 (*SpecEdit) OperationsSecurityReplace added in v1.16.0

func (se *SpecEdit) OperationsSecurityReplace(pathMethodsInclude, pathMethodsExclude []string, securityRequirement map[string][]string)

OperationsSecurityReplace rplaces the security requirement object of operations that meets its include and exclude filters. SecurityRequirement is specified by OpenAPI/Swagger standard version 3. See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#securityRequirementObject

func (*SpecEdit) OperationsSetDeprecated added in v1.16.0

func (se *SpecEdit) OperationsSetDeprecated(newDeprecated bool)

func (*SpecEdit) ParamPathNamesModify added in v1.16.0

func (se *SpecEdit) ParamPathNamesModify(xf func(string) string) (map[string]string, error)

ParamPathNamesModify should result in a spec that validates and performs post-modification validation.

func (*SpecEdit) PathsModify added in v1.16.0

func (se *SpecEdit) PathsModify(opts SpecPathsModifyOpts) error

func (*SpecEdit) PathsNullToEmpty added in v1.16.0

func (se *SpecEdit) PathsNullToEmpty()

PathsNullToEmpty 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 (*SpecEdit) SchemaKeysModify added in v1.16.0

func (se *SpecEdit) SchemaKeysModify(xf func(string) string) error

func (*SpecEdit) SchemaPropertiesSetOptional added in v1.16.0

func (se *SpecEdit) SchemaPropertiesSetOptional(rxOptional *regexp.Regexp) error

SchemaPropertiesSetOptional sets properties as optional if the description matches a regexp such as var rxOptionalDefault = regexp.MustCompile(`(?i)\boptional\b`)

func (*SpecEdit) SchemaRefsFlatten added in v1.16.0

func (se *SpecEdit) SchemaRefsFlatten() error

SchemaRefsFlatten flattens Schema refs.

func (*SpecEdit) SchemaRefsModify added in v1.16.0

func (se *SpecEdit) SchemaRefsModify(xf func(string) string)

SchemaRefsModify modifys schema reference JSON pointers. The xf function must return the entire JSON pointer.

func (*SpecEdit) SchemaRefsModifyRx added in v1.16.0

func (se *SpecEdit) SchemaRefsModifyRx(rx *regexp.Regexp, repl string)

SchemaRefsModifyRx modifies `$ref` reference strings that match a supplied `*regexp.Regexp` and replaces that with a string. It was originally designed to convert `#schemas/` to `#components/schemas/`.

func (*SpecEdit) SchemaSetAdditionalPropertiesTrue added in v1.16.0

func (se *SpecEdit) SchemaSetAdditionalPropertiesTrue(pointerBase string) []string

func (*SpecEdit) SchemasFlatten added in v1.16.0

func (se *SpecEdit) SchemasFlatten()

func (*SpecEdit) SchemasFlattenSchemaRef added in v1.16.0

func (se *SpecEdit) SchemasFlattenSchemaRef(baseName, schName string, schRef *oas3.SchemaRef)

func (*SpecEdit) SchemasSetDeprecated added in v1.16.0

func (se *SpecEdit) SchemasSetDeprecated(newDeprecated bool)

func (*SpecEdit) SecuritySchemeAddBearertoken added in v1.16.0

func (se *SpecEdit) SecuritySchemeAddBearertoken(schemeName, bearerFormat string, inclTags, skipTags []string) error

SecuritySchemeAddBearertoken adds bearer token auth to spec and operations.

func (*SpecEdit) SecuritySchemeApikeyAddDefinition added in v1.16.0

func (se *SpecEdit) SecuritySchemeApikeyAddDefinition(schemeName, location, name string) error

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

func (*SpecEdit) SecuritySchemeApikeyAddOperations added in v1.16.0

func (se *SpecEdit) SecuritySchemeApikeyAddOperations(tags []string, keyName string) error

func (*SpecEdit) SecuritySchemeBearertokenAddDefinition added in v1.16.0

func (se *SpecEdit) SecuritySchemeBearertokenAddDefinition(schemeName, bearerFormat string) error

func (*SpecEdit) SecuritySchemeBearertokenAddOperationsByTags added in v1.16.0

func (se *SpecEdit) SecuritySchemeBearertokenAddOperationsByTags(schemeName string, inclTags, skipTags []string) error

func (*SpecEdit) SetDeprecatedImplicit added in v1.16.0

func (se *SpecEdit) SetDeprecatedImplicit()

func (*SpecEdit) SetOperation added in v1.16.0

func (se *SpecEdit) SetOperation(path, method string, op oas3.Operation) error

SetOperation sets an operation in a OpenAPI Specification.

func (*SpecEdit) SpecSet added in v1.14.0

func (se *SpecEdit) SpecSet(spec *openapi3.Spec)

func (*SpecEdit) SpecTagsCondense added in v1.16.0

func (se *SpecEdit) SpecTagsCondense()

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

func (*SpecEdit) TagsModify added in v1.14.0

func (se *SpecEdit) TagsModify(mapTagsOldToNew map[string]string)

TagsModify renames tags using mapping of old tags to new tags.

func (*SpecEdit) TagsModifyMore added in v1.14.0

func (se *SpecEdit) TagsModifyMore(opts *TagsModifyOpts)

func (*SpecEdit) TagsOrder added in v1.16.0

func (se *SpecEdit) TagsOrder(explicitSortedTagNames []string) error

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

func (*SpecEdit) ValidateFixOperationPathParameters added in v1.16.0

func (se *SpecEdit) ValidateFixOperationPathParameters(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 (*SpecEdit) ValidateFixOperationResponseTypes added in v1.16.0

func (se *SpecEdit) ValidateFixOperationResponseTypes(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`.

type SpecMoreModifyMultiOpts

type SpecMoreModifyMultiOpts struct {
	OperationsDeleteFunc     func(opPath, opMethod 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 TagsModifyOpts added in v1.13.0

type TagsModifyOpts struct {
	// TagURLsMap is a map where the keys are the new tags to add in CSV format while the values
	// are a set of URL suffixes.
	TagURLsMap map[string][]string
	// TagsMap is a map where the keys are the old tag to modify and the value is the tag to use.
	TagsMap map[string]string
}

TagsModifyOpts is used with `SpecEdit.TagsModifyMore()`.

func (*TagsModifyOpts) ModifyTagsOperationFunc added in v1.13.0

func (tmo *TagsModifyOpts) ModifyTagsOperationFunc(path, method string, op *oas3.Operation)

ModifyTagsOperationFunc satisfies the function signature used in `openapi3.VisitOperations`.`

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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