Skip to content

scukonick/kin-openapi

 
 

Repository files navigation

Forked from: github.com/jban332/kin-openapi

Overview

This library provides packages for dealing with OpenAPI specifications.

Status

Current

TODO

  • More tests

Dependencies

Credits

License

Alternatives

  • go-openapi
    • Provides a stable and well-tested implementation of OpenAPI version 2.
  • See this list.

Packages

  • jsoninfo
    • Provides information and functions for marshalling/unmarshalling JSON. The purpose is a clutter-free implementation of JSON references and OpenAPI extension properties.
  • openapi2
    • Parses/writes OpenAPI 2.
  • openapi2conv
    • Converts OpenAPI 2 specification into OpenAPI 3 specification.
  • openapi3
    • Parses/writes OpenAPI 3. Includes OpenAPI schema / JSON schema valdation.
  • openapi3filter
    • Validates that HTTP request and HTTP response match an OpenAPI specification file.
  • openapi3gen
    • Generates OpenAPI 3 schemas for Go types.
  • pathpattern
    • Support for OpenAPI style path patterns.

Getting started

Loading OpenAPI document

Use SwaggerLoader, which resolves all JSON references:

swagger, err := openapi3.NewSwaggerLoader().LoadFromFile("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

import (
  "github.com/marusama/kin-openapi/openapi3"
  "github.com/marusama/kin-openapi/openapi3filter"
  "net/http"
)

var router = openapi3filter.NewRouter().WithSwaggerFromFile("swagger.json")

func ValidateRequest(req *http.Request) {
  openapi3filter.ValidateRequest(nil, &openapi3filter.ValidateRequestInput {
    Request: req,
    Router:  router,
  })
  
  // Get response

  openapi3filter.ValidateResponse(nil, &openapi3filter.ValidateResponseInput {
    // ...
  })
}

Having extension properties in your own structs

The package jsoninfo marshals/unmarshal JSON extension properties ("x-someExtension")

Usage looks like:

type Example struct {
  // Allow extension properties ("x-someProperty")
  openapi3.ExtensionProps
  
  // Normal properties
  SomeField float64
}

func (example *Example) MarshalJSON() ([]byte, error) {
  return jsoninfo.MarshalStrictStruct(example)
}

func (example *Example) UnmarshalJSON(data []byte) error {
  return jsoninfo.UnmarshalStrictStruct(data, example)
}

About

OpenAPI 3.0 implementation for Go (parsing, converting, validating)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%