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

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

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倍出图效率,让品牌能够快速上架。

下拉加载更多