

GitHub - getkin/kin-openapi: OpenAPI 3.0 implementation for Go (parsing, convert...
source link: https://github.com/getkin/kin-openapi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md
Introduction
A Go project for handling OpenAPI files. We target the latest OpenAPI version (currently 3), but the project contains support for older OpenAPI versions too.
Licensed under the MIT License.
Contributors and users
The project has received pull requests from many people. Thanks to everyone!
Here's some projects that depend on kin-openapi:
- github.com/getkin/kin - "A configurable backend"
- github.com/danielgtaylor/apisprout - "Lightweight, blazing fast, cross-platform OpenAPI 3 mock server with validation"
- github.com/deepmap/oapi-codegen - Generate Go server boilerplate from an OpenAPI 3 spec
- (Feel free to add your project by creating an issue or a pull request)
Alternative projects
- go-openapi
- Supports OpenAPI version 2.
- See this list.
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
- openapi3gen (godoc)
- Generates
*openapi3.Schema
values for Go types.
- Generates
- pathpattern (godoc)
- Matches strings with OpenAPI path patterns ("/path/{parameter}")
Some recipes
Loading OpenAPI document
Use SwaggerLoader
, which resolves all JSON references:
swagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile("swagger.json")
Getting OpenAPI operation that matches request
func GetOperation(httpRequest *http.Request) (*openapi3.Operation, error) { // Load Swagger file router := openapi3filter.NewRouter().WithSwaggerFromFile("swagger.json") // Find route route, _, err := router.FindRoute("GET", req.URL.String()) if err!=nil { return nil, err } // Get OpenAPI 3 operation return route.Operation }
Validating HTTP requests/responses
package main import ( "bytes" "context" "encoding/json" "log" "net/http" "github.com/getkin/kin-openapi/openapi3filter" ) func main() { router := openapi3filter.NewRouter().WithSwaggerFromFile("swagger.json") ctx := context.TODO() httpReq, _ := http.NewRequest(http.MethodGet, "/items", nil) // Find route route, pathParams, _ := router.FindRoute(httpReq.Method, httpReq.URL) // Validate request requestValidationInput := &openapi3filter.RequestValidationInput{ Request: httpReq, PathParams: pathParams, Route: route, } if err := openapi3filter.ValidateRequest(ctx, requestValidationInput); err != nil { panic(err) } var ( respStatus = 200 respContentType = "application/json" respBody = bytes.NewBufferString(`{}`) ) log.Println("Response:", respStatus) responseValidationInput := &openapi3filter.ResponseValidationInput{ RequestValidationInput: requestValidationInput, Status: respStatus, Header: http.Header{ "Content-Type": []string{ respContentType, }, }, } if respBody != nil { data, _ := json.Marshal(respBody) responseValidationInput.SetBodyBytes(data) } // Validate response. if err := openapi3filter.ValidateResponse(ctx, responseValidationInput); err != nil { panic(err) } }
Custom content type for body of HTTP request/response
By default, the library parses a body of HTTP request and response
if it has one of the next 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 []byte) (interface{}, error) { // Decode body to a primitive, []inteface{}, or map[string]interface{}. }
Recommend
-
141
OpenAPI Testing Meqanized Meqa generates and runs test suites using your OpenAPI (formerly Swagger) spec in YAML. It makes REST API testing easy by generating useful test patterns - no coding needed. Highlights Unde...
-
166
aliyun/aliyun-openapi-php-sdk: [Abandoned] Open API SDK for PHP developers Skip to content...
-
84
README.md yii2-openapi Note: The status of this code is experimental. Use at your own risk. REST API...
-
60
README.md OpenAPI SDK для Java Данный проект представляет собой инструментарий на языке Java для работы с OpenAPI Тинькофф Инвестиции, которы...
-
57
The OpenAPI Specification ...
-
273
README.md
-
7
KIN Summer Workshop 13-14 June 2012 KIN Summer Workshop 13-14 June 2012 Knowledge and Innovation Network (KIN) Summer Workshop
-
4
-
8
Hawaii A dotnet CLI tool to generate type-safe F# clients from OpenAPI documents. This project is still work in progress. You can watch the live coding sessions as a playlist published on
-
4
Clicking with Your Kin How sperm whale sounds are like team uniforms. ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK