kin-openapi

kin-openapi

Go语言OpenAPI规范解析和验证库

kin-openapi是一个专门用于解析和验证OpenAPI规范的Go语言库。它支持OpenAPI 2.0和3.0版本,提供文档序列化、反序列化、验证以及HTTP请求/响应校验等功能。该库还允许自定义内容类型解码和数组唯一性检查,被广泛应用于各类Go项目中。作为处理OpenAPI规范的专业工具,kin-openapi具有强大的功能和良好的扩展性。

OpenAPIGoAPI文档验证路由Github开源项目

CI Go Report Card GoDoc Join Gitter Chat Channel -

Introduction

A Go project for handling OpenAPI files. We target:

Licensed under the MIT License.

Contributors, users and sponsors

The project has received pull requests from many people. Thanks to everyone!

Please, give back to this project by becoming a sponsor.

Here's some projects that depend on kin-openapi:

Alternatives

Be sure to check OpenAPI Initiative's great tooling list as well as OpenAPI.Tools.

Structure

  • openapi2 (godoc)
    • Support for OpenAPI 2 files, including serialization, deserialization, and validation.
  • openapi2conv (godoc)
    • Converts OpenAPI 2 files into OpenAPI 3 files.
  • openapi3 (godoc)
    • Support for OpenAPI 3 files, including serialization, deserialization, and validation.
  • openapi3filter (godoc)
    • Validates HTTP requests and responses
    • Provides a gorilla/mux router for OpenAPI operations
  • openapi3gen (godoc)
    • Generates *openapi3.Schema values for Go types.

Some recipes

Validating an OpenAPI document

go run github.com/getkin/kin-openapi/cmd/validate@latest [--circular] [--defaults] [--examples] [--ext] [--patterns] -- <local YAML or JSON file>

Loading OpenAPI document

Use openapi3.Loader, which resolves all references:

loader := openapi3.NewLoader() doc, err := loader.LoadFromFile("my-openapi-spec.json")

Getting OpenAPI operation that matches request

loader := openapi3.NewLoader() doc, _ := loader.LoadFromData([]byte(`...`)) _ = doc.Validate(loader.Context) router, _ := gorillamux.NewRouter(doc) route, pathParams, _ := router.FindRoute(httpRequest) // Do something with route.Operation

Validating HTTP requests/responses

package main import ( "context" "fmt" "net/http" "github.com/getkin/kin-openapi/openapi3" "github.com/getkin/kin-openapi/openapi3filter" "github.com/getkin/kin-openapi/routers/gorillamux" ) func main() { ctx := context.Background() loader := &openapi3.Loader{Context: ctx, IsExternalRefsAllowed: true} doc, _ := loader.LoadFromFile(".../My-OpenAPIv3-API.yml") // Validate document _ = doc.Validate(ctx) router, _ := gorillamux.NewRouter(doc) httpReq, _ := http.NewRequest(http.MethodGet, "/items", nil) // Find route route, pathParams, _ := router.FindRoute(httpReq) // Validate request requestValidationInput := &openapi3filter.RequestValidationInput{ Request: httpReq, PathParams: pathParams, Route: route, } _ = openapi3filter.ValidateRequest(ctx, requestValidationInput) // Handle that request // --> YOUR CODE GOES HERE <-- responseHeaders := http.Header{"Content-Type": []string{"application/json"}} responseCode := 200 responseBody := []byte(`{}`) // Validate response responseValidationInput := &openapi3filter.ResponseValidationInput{ RequestValidationInput: requestValidationInput, Status: responseCode, Header: responseHeaders, } responseValidationInput.SetBodyBytes(responseBody) _ = openapi3filter.ValidateResponse(ctx, responseValidationInput) }

Custom content type for body of HTTP request/response

By default, the library parses a body of the HTTP request and response if it has one of the following content types: "text/plain" or "application/json". To support other content types you must register decoders for them:

func main() { // ... // Register a body's decoder for content type "application/xml". openapi3filter.RegisterBodyDecoder("application/xml", xmlBodyDecoder) // Now you can validate HTTP request that contains a body with content type "application/xml". requestValidationInput := &openapi3filter.RequestValidationInput{ Request: httpReq, PathParams: pathParams, Route: route, } if err := openapi3filter.ValidateRequest(ctx, requestValidationInput); err != nil { panic(err) } // ... // And you can validate HTTP response that contains a body with content type "application/xml". if err := openapi3filter.ValidateResponse(ctx, responseValidationInput); err != nil { panic(err) } } func xmlBodyDecoder(body io.Reader, h http.Header, schema *openapi3.SchemaRef, encFn openapi3filter.EncodingFn) (decoded any, err error) { // Decode body to a primitive, []any, or map[string]any. }

Custom function to check uniqueness of array items

By default, the library checks unique items using the following predefined function:

func isSliceOfUniqueItems(xs []any) bool { s := len(xs) m := make(map[string]struct{}, s) for _, x := range xs { key, _ := json.Marshal(&x) m[string(key)] = struct{}{} } return s == len(m) }

In the predefined function json.Marshal is used to generate a string that can be used as a map key which is to check the uniqueness of an array when the array items are objects or arrays. You can register you own function according to your input data to get better performance:

func main() { // ... // Register a customized function used to check uniqueness of array. openapi3.RegisterArrayUniqueItemsChecker(arrayUniqueItemsChecker) // ... other validate codes } func arrayUniqueItemsChecker(items []any) bool { // Check the uniqueness of the input slice }

Custom function to change schema error messages

By default, the error message returned when validating a value includes the error reason, the schema, and the input value.

For example, given the following schema:

{ "type": "string", "allOf": [ { "pattern": "[A-Z]" }, { "pattern": "[a-z]" }, { "pattern": "[0-9]" }, { "pattern": "[!@#$%^&*()_+=-?~]" } ] }

Passing the input value "secret" to this schema will produce the following error message:

string doesn't match the regular expression "[A-Z]"
Schema:
  {
    "pattern": "[A-Z]"
  }

Value:
  "secret"

Including the original value in the error message can be helpful for debugging, but it may not be appropriate for sensitive information such as secrets.

To disable the extra details in the schema error message, you can set the openapi3.SchemaErrorDetailsDisabled option to true:

func main() { // ... // Disable schema error detailed error messages openapi3.SchemaErrorDetailsDisabled = true // ... other validate codes }

This will shorten the error message to present only the reason:

string doesn't match the regular expression "[A-Z]"

For more fine-grained control over the error message, you can pass a custom openapi3filter.Options object to openapi3filter.RequestValidationInput that includes a openapi3filter.CustomSchemaErrorFunc.

func validationOptions() *openapi3filter.Options { options := &openapi3filter.Options{} options.WithCustomSchemaErrorFunc(safeErrorMessage) return options } func safeErrorMessage(err *openapi3.SchemaError) string { return err.Reason }

This will change the schema validation errors to return only the Reason field, which is guaranteed to not include the original value.

Reconciling component $ref types

ReferencesComponentInRootDocument is a useful helper function to check if a component reference coincides with a reference in the root document's component objects fixed fields.

This can be used to determine if two schema definitions are of the same structure, helpful for code generation tools when generating go type models.

doc, err = loader.LoadFromFile("openapi.yml") for _, path := range doc.Paths.InMatchingOrder() { pathItem := doc.Paths.Find(path) if pathItem.Get == nil || pathItem.Get.Responses.Status(200) { continue } for _, s := range pathItem.Get.Responses.Status(200).Value.Content { name, match := ReferencesComponentInRootDocument(doc, s.Schema) fmt.Println(path, match, name) // /record true #/components/schemas/BookRecord } }

CHANGELOG: Sub-v1 breaking API changes

v0.127.0

  • Downgraded github.com/gorilla/mux dep from 1.8.1 to 1.8.0.

v0.126.0

  • openapi3.CircularReferenceError and openapi3.CircularReferenceCounter are removed. openapi3.Loader now implements reference backtracking, so any kind of circular references should be properly resolved.
  • InternalizeRefs now takes a refNameResolver that has access to openapi3.T and more properties of the reference needing resolving.
  • The DefaultRefNameResolver has been updated, choosing names that will be less likely to collide with each other. Because of this internalized specs will likely change slightly.
  • openapi3.Format and openapi3.FormatCallback are removed and the type of openapi3.SchemaStringFormats has changed.

v0.125.0

  • The openapi3filter.ErrFunc and openapi3filter.LogFunc func types now take the validated request's context as first argument.

v0.124.0

  • openapi3.Schema.Type & openapi2.Parameter.Type fields went from a string to the type *Type with methods: Includes, Is, Permits & Slice.

v0.122.0

  • Paths field of openapi3.T is now a pointer
  • Responses field of openapi3.Operation is now a pointer
  • openapi3.Paths went from map[string]*PathItem to a struct with an Extensions field and methods: Set, Value, Len, Map, and New*.
  • openapi3.Callback went from map[string]*PathItem to a struct with an Extensions field and methods: Set, Value, Len, Map, and New*.
  • openapi3.Responses went from map[string]*ResponseRef to a struct with an Extensions field and methods: Set, Value, Len, Map, and New*.
  • (openapi3.Responses).Get(int) renamed to (*openapi3.Responses).Status(int)

v0.121.0

  • Introduce openapi3.RequestBodies (an alias on map[string]*openapi3.ResponseRef) and use it in place of openapi3.Responses for field openapi3.Components.Responses.

v0.116.0

  • Dropped openapi3filter.DefaultOptions. Use &openapi3filter.Options{} directly instead.

v0.113.0

  • The string format email has been removed by default. To use it please call openapi3.DefineStringFormat("email", openapi3.FormatOfStringForEmail).
  • Field openapi3.T.Components is now a pointer.
  • Fields openapi3.Schema.AdditionalProperties and openapi3.Schema.AdditionalPropertiesAllowed are replaced by openapi3.Schema.AdditionalProperties.Schema and openapi3.Schema.AdditionalProperties.Has respectively.
  • Type openapi3.ExtensionProps is now just map[string]any and extensions are accessible through the Extensions field.

v0.112.0

  • (openapi3.ValidationOptions).ExamplesValidationDisabled has been unexported.
  • (openapi3.ValidationOptions).SchemaFormatValidationEnabled has been unexported.
  • (openapi3.ValidationOptions).SchemaPatternValidationDisabled has been unexported.

v0.111.0

  • Changed func (*_) Validate(ctx context.Context) error to func (*_) Validate(ctx context.Context, opts ...ValidationOption) error.
  • openapi3.WithValidationOptions(ctx context.Context, opts *ValidationOptions) context.Context prototype changed to openapi3.WithValidationOptions(ctx context.Context, opts ...ValidationOption) context.Context.

v0.101.0

  • openapi3.SchemaFormatValidationDisabled has been removed in favour of an option openapi3.EnableSchemaFormatValidation() passed to openapi3.T.Validate. The

编辑推荐精选

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

下拉加载更多