openapi

package module
v0.0.0-...-ed82c49 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2024 License: MIT Imports: 20 Imported by: 0

README

Go Docs

openapi

Generate an OpenAPI spec using code in go (golang), serve them easily under /docs without any code generation steps. We support mostly everything in the OpenAPI spec, including callbacks and links. If something is not supported, please open an issue.

Go Support

1.18 and greater

OpenAPI Support
  • 3.1.0
  • 3.0.x

Basic Usage

Run the below example and go to your browser window at http://localhost:8111/docs

package main

import (
	"fmt"
	"net/http"

	"github.com/restk/openapi"
)

func main() {
	type Error struct {
		Message string `json:"message"`
	}
	type Success struct {
		Message string `json:"message"`
	}

	openAPI := openapi.New("My API", "v1.0.0")
	openAPI.Description("My API is a great API")
	openAPI.Server().URL("https://myapi.com").Description("My API URL")

	// define security
	openAPI.BearerAuth()

	// define security
	openAPI.OAuth2().Implicit().AuthorizationURL("https://api.example.com/oauth2/authorize").Scopes(map[string]string{
		"read_users":  "read users",
		"write_users": "write to users",
	})

	// apply security (globally)
	openAPI.Security("OAuth2", []string{"read_users", "write_users"})

	// registering a URL (operation)
	type LoginRequest struct {
		Username string `json:"username" doc:"username to login with" maxLength:"25"`
		Password string `json:"password" doc:"password to login with" maxLength:"50"`
	}

	login := openAPI.Register(&openapi.Operation{
                OperationID: "loginUser",
		Method: "POST",
		Path:   "/login",
	})

	login.Request().Body(LoginRequest{})
	login.Response(http.StatusOK).ContentType("text/plain").Body(openapi.StringType)
	login.Response(http.StatusOK).Body(Success{})

	// registering a URL (operation)

	type User struct {
		ID   string `json:"id" doc:"ID of user" example:"2"`
		Name string `json:"name" doc:"Name of user" example:"joe"`
		Age  int    `json:"age" doc:"Age of user" example:"32"`
	}

	getUser := openAPI.Register(&openapi.Operation{
                OperationID: "getUser",
		Method: "GET",
		Path:   "/users/{userId}",
	})

	getUser.Request().PathParam("userId", openapi.IntType).Required(true)
	getUser.Request().QueryParam("age", &openapi.IntType).Example("12").Description("Age of user") // pointers make the query param optional
	getUser.Request().QueryParam("email", openapi.StringType).Example("joe@gmail.com").Description("Email of user")

	getUser.Response(http.StatusOK).Body(User{}).Example(`{id: 3, name: "joe", age: 5}`) // override example from User struct
	getUser.Response(http.StatusForbidden).Body(Error{})                                 // default content type is application/json

	bytes, err := openAPI.OpenAPI().YAML()
	if err != nil {
		panic(err)
	}

	fmt.Println(string(bytes))

	// serve under /docs using scalar (visit http://localhost:8111/docs)
	scalar := openapi.Scalar(openAPI.OpenAPI(), map[string]any{
		"theme": "purple",
	})

	fmt.Println("Serving docs at http://localhost:8111/docs")

	docs := func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write(scalar)
	}

	http.HandleFunc("/docs", docs)
	http.ListenAndServe(":8111", nil)

Serving docs

You can serve docs easily using our helper functions.

Scalar

net/http

	scalar := openapi.Scalar(openAPI.OpenAPI(), map[string]any{
		"theme": "purple", // try solarized, moon, mars, saturn
	})

	docs := func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write(scalar)
	}

	http.HandleFunc("/docs", docs)
	http.ListenAndServe(":8111", nil)

gin
	scalar := openapi.Scalar(openAPI.OpenAPI(), map[string]any{
		"theme": "purple", // try solarized, moon, mars, saturn
	})

	router.GET("/docs", func(c *gin.Context) {
		c.Data(http.StatusOK, "text/html", scalar)
	})
anything else

openapi.Scalar() returns a []byte which contains text/html. You can serve it under any HTTP library by writing the bytes and setting the Content-Type header to text/html

	scalar := openapi.Scalar(openAPI.OpenAPI(), map[string]any{
		"theme": "purple", // try solarized, moon, mars, saturn
	})

	// set content header to text/html
	// write scalar ([]byte)

Creating an API

To create an API, you can call openApi.New(title, version)


openAPI := openapi.New("My API", "v1.0.0")
openAPI.Description("My API is a great API")
openAPI.Server().URL("https://myapi.com").Description("My API URL")
openAPI.Contact().Name("Joe").Email("joe@gmail.com")
openAPI.License().Name("MIT").URL("myapi.com/license")

Register (returns an Operation)

To add an endpoint to the API, simply call .Register(), make sure to set an OperationID which is used for other functions

post := openAPI.Register(&openapi.Operation{
  OperationID: "createUser",
  Method: "POST",
  Path:   "/users",
})

patch := openAPI.Register(&openapi.Operation{
  OperationID: "patchUser",
  Method: "PATCH",
  Path:   "/users/{id}",
  Tags: []string{"users"},
})

delete := openAPI.Register(&openapi.Operation{
  OperationID: "deleteUser",
  Method: "DELETE",
  Path:   "/users/{id}",
})

Request

To add a Request to an Operation which is returned by the Register method, you can call Request()

// You can describe structs via the tags `doc`, `example`, see Struct Tags Table for all tags
type ExampleStruct struct {
  Name string `json:"name" doc:"name of person" example:"joe" maxLength:"50"`
}

// set the default content type, note: application/json is already the default content type
.Request().DefaultContentType("application/json")

// override content type for the next Body() call 
.Request().ContentType("application/xml").Body(ExampleStruct{})

// body (this is served as DefaultContentType("application/json") since ContentType only overrides one Body call)
.Request().Body(ExampleStruct{})

// override example
.Request().Body(ExampleStruct{}).Example("{ name: 'joe' }")

// multiple examples
body := .Request().Body(ExampleStruct{})
body.AddExample().Value("{ name: 'joe' }")
body.AddExample().ExternalValue("http://myapi.com/example.json")

// path params
.Request().PathParam("userId", openapi.IntType).Required(true)

// query params
.Request().QueryParam("age", &openapi.IntType).Example("12").Description("Age of user") 
.Request().QueryParam("email", openapi.StringType).
           Example("joe@gmail.com").
           Description("Email of user").
           Required(true)

// query param with multiple examples
bio := .Request().QueryParam("bio", &openapi.StringType).Description("Bio of user")
bio.AddExample().Value("I was born in Canada")
bio.AddExample().Value("I was bron in the U.S")

// cookie param
.Request().CookieParam("session", &openapi.StringType).Description("Session cookie")

// generic param
.Request().Param("path", "userId", openAPI.IntType).Required(true)

Response

You can add a response by calling Response(status)

// basic response
.Response(http.StatusOK).ContentType("text/plain").Body(openapi.StringType)

// you can add multiple content types for the same Response
.Response(http.StatusOK).Body(Success{})
.Response(http.StatusOK).ContentType("text/plain").Body(openapi.StringType)

// error response
.Response(http.StatusForbidden).Body(Error{})

// override example 
.Response(http.StatusOK).Body(User{}).Example(`{id: 3, name: "joe", age: 5}`)

// multiple examples
body := .Response(http.StatusOK).Body(User{})
body.AddExample().Value("{id: 3, name: "joe", age: 5}")
body.AddExample().ExternalValue("http://myapi.com/user.json")

// headers
.Response(http.StatusOK).Header("X-Rate-Limit-Remaining", openapi.IntType)

// link
.Response(http.StatusOK).Body(User{}).Link("GetUserByUserId").
	OperationId("getUser").
	Description("The `id` value returned in the response can be used as the `userId` parameter in `GET /users/{userId}`").
        AddParam("userId", "$response.body#/id")

Struct Tags

You use tags in structs to define extra information on fields, such as their limits, docs, and examples. See the tag table below for entire list of tags.

type Example struct {
  // doc and example
  ID int `json:"id" doc:"ID of User" example:"1"`

  // minLength and maxLength
  Name string `json:"name" doc:"Name of User" example:"joe" minLength:"3" maxLength:"30"`
}
Tags
Tag Description Example
doc Describe the field doc:"Who to greet"
format Format hint for the field format:"date-time"
enum A comma-separated list of possible values enum:"one,two,three"
default Default value default:"123"
minimum Minimum (inclusive) minimum:"1"
exclusiveMinimum Minimum (exclusive) exclusiveMinimum:"0"
maximum Maximum (inclusive) maximum:"255"
exclusiveMaximum Maximum (exclusive) exclusiveMaximum:"100"
multipleOf Value must be a multiple of this value multipleOf:"2"
minLength Minimum string length minLength:"1"
maxLength Maximum string length maxLength:"80"
pattern Regular expression pattern pattern:"[a-z]+"
patternDescription Description of the pattern used for errors patternDescription:"alphanum"
minItems Minimum number of array items minItems:"1"
maxItems Maximum number of array items maxItems:"20"
uniqueItems Array items must be unique uniqueItems:"true"
minProperties Minimum number of object properties minProperties:"1"
maxProperties Maximum number of object properties maxProperties:"20"
example Example value example:"123"
readOnly Sent in the response only readOnly:"true"
writeOnly Sent in the request only writeOnly:"true"
deprecated This field is deprecated deprecated:"true"
hidden Hide field/param from documentation hidden:"true"
dependentRequired Required fields when the field is present dependentRequired:"one,two"

Built-in string formats:

Format Description Example
date-time Date and time in RFC3339 format 2021-12-31T23:59:59Z
date-time-http Date and time in HTTP format Fri, 31 Dec 2021 23:59:59 GMT
date Date in RFC3339 format 2021-12-31
time Time in RFC3339 format 23:59:59
email / idn-email Email address kari@example.com
hostname Hostname example.com
ipv4 IPv4 address 127.0.0.1
ipv6 IPv6 address ::1
uri / iri URI https://example.com
uri-reference / iri-reference URI reference /path/to/resource
uri-template URI template /path/{id}
json-pointer JSON Pointer /path/to/field
relative-json-pointer Relative JSON Pointer 0/1
regex Regular expression [a-z]+
uuid UUID 550e8400-e29b-41d4-a716-446655440000

Examples

Examples show an example for a type, they can be set in various places

Struct
type User struct {
  Name string `json:"name" example:"joe"`
}
PathParam / QueryParam / CookieParam and Param

Example below works for all param functions: PathParam, QueryParam, CookieParam and Param

// single example
getUser.Request().QueryParam("age", &openapi.IntType).Example("21")

// multiple examples
param := getUser.Request().QueryParam("age", &openapi.IntType)
param.AddExample().Value("21")
param.AddExample().Value("41")

Body

If you pass a Struct in Body() and that Struct has an example, calling Example() on Body will override the example on the struct.

// single
getUser.Response(http.StatusOK).Body(User{}).Example(`{id: 3, name: "joe", age: 5}`)

// multiple
bdy := getUser.Response(http.StatusOK).Body(User{}).Example(`{id: 3, name: "joe", age: 5}`)
bdy.AddExample().Value("{id: 3, name: "joe", age: 5}")
bdy.AddExample().ExternalValue("http://myapi.com/user-example.json")

Security

You can add security schemas at the top level, then you can apply them either globally or to an individual operation

// Bearer
openAPI.BearerAuth()

// API key
openAPI.ApiKeyAuth("Header-For-Api-Key")

// OpenID
openAPI.OpenID("URL to OpenID Connect URL")

// OAuth2
openAPI.OAuth2().Implicit().AuthorizationURL("https://api.example.com/oauth2/authorize").Scopes(map[string]string{
  "read_users":  "read users",
  "write_users": "write to users",
})

// Custom Security Schema
openAPI.SecuritySchema(name, *SecuritySchema)

// Apply security (globally)
openAPI.Security("OAuth2", []string{"read_users", "write_users"})

// Apply Security (to one operation)
post := openAPI.Register(&openapi.Operation{
  OperationID: "createUser",
  Method: "POST",
  Path:   "/users",
})

post.Security("OAuth2", []string{"write_users"})

Links can be added by calling Link() on an Operation, see below example.

type User struct {
  ID int `json:"id"`
}

createUser := openAPI.Register(&openapi.Operation{
    OperationID: "createUser",
    Method: "POST",
    Path: "/users",
})

getUser := openAPI.Register(&openapi.Operation{
    OperationID: "getUser",
    Method: "GET",
    Path: "/users/{userId}",
})

// we call link on the createUser operation which will give us a link to the getUser operation where we can use the returned user.id in the body
response := createUser.Response(http.StatusOK)
response.Body(User{})

response.Link("GetUserByUserId").
	OperationID("getUser").
	Description("The id value returned in the response can be used as the userId parameter in GET /users/{userId}").
        AddParam("userId", "$response.body#/id")


Callbacks

Callbacks can be added by calling Callback() on an Operation. Callbacks themselves are also an Operation so you can call Request(), Response() on them as usual


type CallbackResponse struct {
  CallbackURL string `json:"callbackUrl" format:"uri"`
}

type Event struct {
  Message string `json:"message"`
}

o := openAPI.Register(&openapi.Operation{
  OperationID: "eventSubscribe",
  Method: "POST",
  Path:   "/subscribe",
})

o.Response(http.StatusOK).Body(&CallbackResponse{})

callback := o.Callback("myEvent", &openapi.Operation{
  Method: "POST",
  Path:   "{$request.body#/callbackUrl}",
})

callback.Request().Body(&Event{})
callback.Response(200).Body(openapi.StringType).Example("Your server returns this code if it accepts the callback")

Credits

The OpenAPI implementation is taken from https://github.com/danielgtaylor/huma (and credits to @danielgtaylor), we extend it here to be usable outside of Huma via the Builder Pattern.

restk (rest-kit)

restk helps you rapidly create REST APIs in Golang

Documentation

Overview

Copyright 2024 Arianit Uka

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright 2020 Daniel G. Taylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright 2020 Daniel G. Taylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright 2020 Daniel G. Taylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright 2020 Daniel G. Taylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Copyright 2020 Daniel G. Taylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

View Source
const (
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeString  = "string"
	TypeArray   = "array"
	TypeObject  = "object"
)

JSON Schema type constants

Variables

View Source
var (
	IntType   = int(0)
	Int8Type  = int8(0)
	Int16Type = int16(0)
	Int32Type = int32(0)
	Int64Type = int64(0)

	UintType    = uint(0)
	Uint8Type   = uint8(0)
	Uint16Type  = uint16(0)
	Uint32Type  = uint32(0)
	Uint64Type  = uint64(0)
	UintPtrType = uintptr(0)

	Float32Type = float32(0)
	Float64Type = float64(0)

	Complex64Type  = complex64(0)
	Complex128Type = complex128(0)

	StringType = ""
	BoolType   = false
	ByteType   = byte(0)
	RuneType   = rune(0)
)

Basic initialized types that can be easily passed to any Body() in builder.go

View Source
var ErrSchemaInvalid = errors.New("schema is invalid")

ErrSchemaInvalid is sent when there is a problem building the schema.

Functions

func DefaultSchemaNamer

func DefaultSchemaNamer(t reflect.Type, hint string) string

DefaultSchemaNamer provides schema names for types. It uses the type name when possible, ignoring the package name. If the type is generic, e.g. `MyType[SubType]`, then the brackets are removed like `MyTypeSubType`. If the type is unnamed, then the name hint is used. Note: if you plan to use types with the same name from different packages, you should implement your own namer function to prevent issues. Nested anonymous types can also present naming issues.

func Scalar

func Scalar(openAPI *OpenAPI, configuration map[string]any) []byte

Scalar returns text/HTML for serving an OpenAPI spec using the scalar library.

func Validate

func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any, res *ValidateResult)

Validate an input value against a schema, collecting errors in the validation result object. If successful, `res.Errors` will be empty. It is suggested to use a `sync.Pool` to reuse the PathBuffer and ValidateResult objects, making sure to call `Reset()` on them before returning them to the pool.

registry := openapi.NewMapRegistry("#/prefix", openapi.DefaultSchemaNamer)
schema := openapi.SchemaFromType(registry, reflect.TypeOf(MyType{}))
pb := openapi.NewPathBuffer([]byte(""), 0)
res := &openapi.ValidateResult{}

var value any
json.Unmarshal([]byte(`{"foo": "bar"}`), &v)
openapi.Validate(registry, schema, pb, openapi.ModeWriteToServer, value, res)
for _, err := range res.Errors {
	fmt.Println(err.Error())
}

Types

type AddOpFunc

type AddOpFunc func(oapi *OpenAPI, op *Operation)

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder provides builders for building an OpenAPI spec from code

func New

func New(title, version string) *Builder

New returns an OpenAPI builder that can be used to easily generate OpenAPI specs from code.

func (*Builder) ApiKeyAuth

func (b *Builder) ApiKeyAuth(header string) *Builder

ApiKeyAuth adds a ApiKeyAuth security schema. We expect the API key to be in a Header and you specify the header as the argument to this function

func (*Builder) BasicAuth

func (b *Builder) BasicAuth() *Builder

BasicAuth adds a BasicAuth security schema

func (*Builder) BearerAuth

func (b *Builder) BearerAuth() *Builder

BearerAuth adds a BearerAuth security schema

func (*Builder) Contact

func (b *Builder) Contact() *Builder

Contact adds a contact

func (*Builder) Description

func (b *Builder) Description(description string) *Builder

Description sets the description for the API

func (*Builder) License

func (b *Builder) License() *Builder

License adds a License to the OpenAPI info object

func (*Builder) OAuth2

func (b *Builder) OAuth2() *OAuth2Builder

func (*Builder) OpenAPI

func (b *Builder) OpenAPI() *OpenAPI

OpenAPI returns the OpenAPI struct.

func (*Builder) OpenID

func (b *Builder) OpenID(url string) *Builder

OpenID adds a OpenID security schema. url is an OpenId Connect URL to discover OAuth2

func (*Builder) Register

func (b *Builder) Register(op *Operation) *OperationBuilder

Register registers a new Operation.

func (*Builder) Registry

func (b *Builder) Registry() Registry

Registry returns the Registry.

func (*Builder) Security

func (b *Builder) Security(securitySchema string, params []string) *Builder

Security sets global security

func (*Builder) SecurityScheme

func (b *Builder) SecurityScheme(name string, scheme *SecurityScheme) *Builder

SecurityScheme adds a custom SecurityScheme.

func (*Builder) Server

func (b *Builder) Server() *ServerBuilder

Server adds a server

func (*Builder) TermsOfService

func (b *Builder) TermsOfService(url string) *Builder

TermsOfService sets url for the terms of service

type Components

type Components struct {
	// Schemas is an object to hold reusable Schema Objects.
	Schemas Registry `yaml:"schemas,omitempty"`

	// Responses is an object to hold reusable Response Objects.
	Responses map[string]*Response `yaml:"responses,omitempty"`

	// Parameters is an object to hold reusable Parameter Objects.
	Parameters map[string]*Param `yaml:"parameters,omitempty"`

	// Examples is an object to hold reusable Example Objects.
	Examples map[string]*Example `yaml:"examples,omitempty"`

	// RequestBodies is an object to hold reusable Request Body Objects.
	RequestBodies map[string]*RequestBody `yaml:"requestBodies,omitempty"`

	// Headers is an object to hold reusable Header Objects.
	Headers map[string]*Header `yaml:"headers,omitempty"`

	// SecuritySchemes is an object to hold reusable Security Scheme Objects.
	SecuritySchemes map[string]*SecurityScheme `yaml:"securitySchemes,omitempty"`

	// Links is an object to hold reusable Link Objects.
	Links map[string]*Link `yaml:"links,omitempty"`

	// Callbacks is an object to hold reusable Callback Objects.
	Callbacks map[string]*PathItem `yaml:"callbacks,omitempty"`

	// PathItems is an object to hold reusable Path Item Objects.
	PathItems map[string]*PathItem `yaml:"pathItems,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Components holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.

components:
  schemas:
    GeneralError:
      type: object
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
    Category:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
    Tag:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
  parameters:
    skipParam:
      name: skip
      in: query
      description: number of items to skip
      required: true
      schema:
        type: integer
        format: int32
    limitParam:
      name: limit
      in: query
      description: max records to return
      required: true
      schema:
        type: integer
        format: int32
  responses:
    NotFound:
      description: Entity not found.
    IllegalInput:
      description: Illegal input for operation.
    GeneralError:
      description: General Error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GeneralError'
  securitySchemes:
    api_key:
      type: apiKey
      name: api_key
      in: header
    petstore_auth:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: https://example.org/api/oauth/dialog
          scopes:
            write:pets: modify pets in your account
            read:pets: read your pets

func (*Components) MarshalJSON

func (c *Components) MarshalJSON() ([]byte, error)

type Contact

type Contact struct {
	// Name of the contact person/organization.
	Name string `yaml:"name,omitempty"`

	// URL pointing to the contact information.
	URL string `yaml:"url,omitempty"`

	// Email address of the contact person/organization.
	Email string `yaml:"email,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Contact information to get support for the API.

name: API Support
url: https://www.example.com/support
email: support@example.com

func (*Contact) MarshalJSON

func (c *Contact) MarshalJSON() ([]byte, error)

type ContactBuilder

type ContactBuilder struct {
	// contains filtered or unexported fields
}

ContactBuilder helps build a contact

func (*ContactBuilder) Email

func (cb *ContactBuilder) Email(email string) *ContactBuilder

Email sets the email for the contact

func (*ContactBuilder) Name

func (cb *ContactBuilder) Name(name string) *ContactBuilder

Name sets the name for the contact

func (*ContactBuilder) URL

func (cb *ContactBuilder) URL(url string) *ContactBuilder

URL sets the URL for the contact

type Encoding

type Encoding struct {
	// ContentType for encoding a specific property. Default value depends on the
	// property type: for object - application/json; for array – the default is
	// defined based on the inner type; for all other cases the default is
	// application/octet-stream. The value can be a specific media type (e.g.
	// application/json), a wildcard media type (e.g. image/*), or a
	// comma-separated list of the two types.
	ContentType string `yaml:"contentType,omitempty"`

	// Headers is a map allowing additional information to be provided as headers,
	// for example Content-Disposition. Content-Type is described separately and
	// SHALL be ignored in this section. This property SHALL be ignored if the
	// request body media type is not a multipart.
	Headers map[string]*Header `yaml:"headers,omitempty"`

	// Style describes how a specific property value will be serialized depending
	// on its type. See Parameter Object for details on the style property. The
	// behavior follows the same values as query parameters, including default
	// values. This property SHALL be ignored if the request body media type is
	// not application/x-www-form-urlencoded or multipart/form-data. If a value is
	// explicitly defined, then the value of contentType (implicit or explicit)
	// SHALL be ignored.
	Style string `yaml:"style,omitempty"`

	// Explode, when true, property values of type array or object generate
	// separate parameters for each value of the array, or key-value-pair of the
	// map. For other types of properties this property has no effect. When style
	// is form, the default value is true. For all other styles, the default value
	// is false. This property SHALL be ignored if the request body media type is
	// not application/x-www-form-urlencoded or multipart/form-data. If a value is
	// explicitly defined, then the value of contentType (implicit or explicit)
	// SHALL be ignored.
	Explode *bool `yaml:"explode,omitempty"`

	// AllowReserved determines whether the parameter value SHOULD allow reserved
	// characters, as defined by [RFC3986] :/?#[]@!$&'()*+,;= to be included
	// without percent-encoding. The default value is false. This property SHALL
	// be ignored if the request body media type is not
	// application/x-www-form-urlencoded or multipart/form-data. If a value is
	// explicitly defined, then the value of contentType (implicit or explicit)
	// SHALL be ignored.
	AllowReserved bool `yaml:"allowReserved,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Encoding is a single encoding definition applied to a single schema property.

requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          id:
            # default is text/plain
            type: string
            format: uuid
          address:
            # default is application/json
            type: object
            properties: {}
          historyMetadata:
            # need to declare XML format!
            description: metadata in XML format
            type: object
            properties: {}
          profileImage: {}
      encoding:
        historyMetadata:
          # require XML Content-Type in utf-8 encoding
          contentType: application/xml; charset=utf-8
        profileImage:
          # only accept png/jpeg
          contentType: image/png, image/jpeg
          headers:
            X-Rate-Limit-Limit:
              description: The number of allowed requests in the current period
              schema:
                type: integer

func (*Encoding) MarshalJSON

func (e *Encoding) MarshalJSON() ([]byte, error)

type ErrorDetail

type ErrorDetail struct {
	// Message is a human-readable explanation of the error.
	Message string `json:"message,omitempty" doc:"Error message text"`

	// Location is a path-like string indicating where the error occurred.
	// It typically begins with `path`, `query`, `header`, or `body`. Example:
	// `body.items[3].tags` or `path.thing-id`.
	Location string `json:"location,omitempty" doc:"Where the error occurred, e.g. 'body.items[3].tags' or 'path.thing-id'"`

	// Value is the value at the given location, echoed back to the client
	// to help with debugging. This can be useful for e.g. validating that
	// the client didn't send extra whitespace or help when the client
	// did not log an outgoing request.
	Value any `json:"value,omitempty" doc:"The value at the given location"`
}

ErrorDetail provides details about a specific error.

func (*ErrorDetail) Error

func (e *ErrorDetail) Error() string

Error returns the error message / satisfies the `error` interface. If a location and value are set, they will be included in the error message, otherwise just the message is returned.

func (*ErrorDetail) ErrorDetail

func (e *ErrorDetail) ErrorDetail() *ErrorDetail

ErrorDetail satisfies the `ErrorDetailer` interface.

type Example

type Example struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Summary is a short summary of the example.
	Summary string `yaml:"summary,omitempty"`

	// Description is a long description of the example. CommonMark syntax MAY
	// be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Value is an embedded literal example. The `value` field and `externalValue`
	// field are mutually exclusive. To represent examples of media types that
	// cannot naturally represented in JSON or YAML, use a string value to contain
	// the example, escaping where necessary.
	Value any `yaml:"value,omitempty"`

	// ExternalValue is a URI that points to the literal example. This provides
	// the capability to reference examples that cannot easily be included in JSON
	// or YAML documents. The `value` field and `externalValue` field are mutually
	// exclusive. See the rules for resolving Relative References.
	ExternalValue string `yaml:"externalValue,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Example value of a request param or body or response header or body.

requestBody:
  content:
    'application/json':
      schema:
        $ref: '#/components/schemas/Address'
      examples:
        foo:
          summary: A foo example
          value: {"foo": "bar"}
        bar:
          summary: A bar example
          value: {"bar": "baz"}

func (*Example) MarshalJSON

func (e *Example) MarshalJSON() ([]byte, error)

type ExampleBuilder

type ExampleBuilder struct {
	// contains filtered or unexported fields
}

ExampleBuilder helps build examples.

func (*ExampleBuilder) Description

func (eb *ExampleBuilder) Description(description string) *ExampleBuilder

Description sets the description for the example.

func (*ExampleBuilder) ExternalValue

func (eb *ExampleBuilder) ExternalValue(uri string) *ExampleBuilder

ExternalValue sets the ExternalValue

func (*ExampleBuilder) Ref

func (eb *ExampleBuilder) Ref(ref string)

Ref sets the ref of the example. This references another example. $ref: '#/components/examples/objectExample'

func (*ExampleBuilder) Summary

func (eb *ExampleBuilder) Summary(summary string) *ExampleBuilder

Summary sets a summary for an example. This is required.

func (*ExampleBuilder) Value

func (eb *ExampleBuilder) Value(value any) *ExampleBuilder

Value sets the value for the example.

type ExternalDocs

type ExternalDocs struct {
	// Description of the target documentation. CommonMark syntax MAY be used for
	// rich text representation.
	Description string `yaml:"description,omitempty"`

	// URL is REQUIRED. The URL for the target documentation. Value MUST be in the
	// format of a URL.
	URL string `yaml:"url"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

ExternalDocs allows referencing an external resource for extended documentation.

description: Find more info here
url: https://example.com

func (*ExternalDocs) MarshalJSON

func (e *ExternalDocs) MarshalJSON() ([]byte, error)
type Header = Param

Header object follows the structure of the Parameter Object with the following changes:

  • name MUST NOT be specified, it is given in the corresponding headers map.

  • in MUST NOT be specified, it is implicitly in header.

  • All traits that are affected by the location MUST be applicable to a location of header (for example, style).

Example:

description: The number of allowed requests in the current period
schema:
  type: integer

type Info

type Info struct {
	// Title of the API.
	Title string `yaml:"title"`

	// Description of the API. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// TermsOfService URL for the API.
	TermsOfService string `yaml:"termsOfService,omitempty"`

	// Contact information to get support for the API.
	Contact *Contact `yaml:"contact,omitempty"`

	// License name & link for using the API.
	License *License `yaml:"license,omitempty"`

	// Version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
	Version string `yaml:"version"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Info object that provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.

title: Sample Pet Store App
summary: A pet store manager.
description: This is a sample server for a pet store.
termsOfService: https://example.com/terms/
contact:
  name: API Support
  url: https://www.example.com/support
  email: support@example.com
license:
  name: Apache 2.0
  url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.1

func (*Info) MarshalJSON

func (i *Info) MarshalJSON() ([]byte, error)

type License

type License struct {
	// Name of the license.
	Name string `yaml:"name"`

	// Identifier SPDX license expression for the API. This field is mutually
	// exclusive with the URL field.
	Identifier string `yaml:"identifier,omitempty"`

	// URL pointing to the license. This field is mutually exclusive with the
	// Identifier field.
	URL string `yaml:"url,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

License name & link for using the API.

name: Apache 2.0
identifier: Apache-2.0

func (*License) MarshalJSON

func (l *License) MarshalJSON() ([]byte, error)

type LicenseBuilder

type LicenseBuilder struct {
	// contains filtered or unexported fields
}

LicenseBuilder helps build a licensea

func (*LicenseBuilder) Identifier

func (lb *LicenseBuilder) Identifier(identifier string) *LicenseBuilder

Identifier sets the identifier

func (*LicenseBuilder) Name

func (lb *LicenseBuilder) Name(name string) *LicenseBuilder

Name sets the license name

func (*LicenseBuilder) URL

func (lb *LicenseBuilder) URL(url string) *LicenseBuilder

URL sets the URL

type Link struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// OperationRef is a relative or absolute URI reference to an OAS operation.
	// This field is mutually exclusive of the operationId field, and MUST point
	// to an Operation Object. Relative operationRef values MAY be used to locate
	// an existing Operation Object in the OpenAPI definition. See the rules for
	// resolving Relative References.
	OperationRef string `yaml:"operationRef,omitempty"`

	// OperationID is the name of an existing, resolvable OAS operation, as
	// defined with a unique operationId. This field is mutually exclusive of the
	// operationRef field.
	OperationID string `yaml:"operationId,omitempty"`

	// Parameters is a map representing parameters to pass to an operation as
	// specified with operationId or identified via operationRef. The key is the
	// parameter name to be used, whereas the value can be a constant or an
	// expression to be evaluated and passed to the linked operation. The
	// parameter name can be qualified using the parameter location [{in}.]{name}
	// for operations that use the same parameter name in different locations
	// (e.g. path.id).
	Parameters map[string]any `yaml:"parameters,omitempty"`

	// RequestBody is a literal value or {expression} to use as a request body
	// when calling the target operation.
	RequestBody any `yaml:"requestBody,omitempty"`

	// Description of the link. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Server object to be used by the target operation.
	Server *Server `yaml:"server,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Link object represents a possible design-time link for a response. The presence of a link does not guarantee the caller’s ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.

Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.

For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.

paths:
  /users/{id}:
    parameters:
    - name: id
      in: path
      required: true
      description: the user identifier, as userId
      schema:
        type: string
    get:
      responses:
        '200':
          description: the user being returned
          content:
            application/json:
              schema:
                type: object
                properties:
                  uuid: # the unique user id
                    type: string
                    format: uuid
          links:
            address:
              # the target link operationId
              operationId: getUserAddress
              parameters:
                # get the `id` field from the request path parameter named `id`
                userId: $request.path.id
  # the path item of the linked operation
  /users/{userid}/address:
    parameters:
    - name: userid
      in: path
      required: true
      description: the user identifier, as userId
      schema:
        type: string
    # linked operation
    get:
      operationId: getUserAddress
      responses:
        '200':
          description: the user's address

func (*Link) MarshalJSON

func (l *Link) MarshalJSON() ([]byte, error)

type LinkBuilder

type LinkBuilder struct {
	// contains filtered or unexported fields
}

LinkBuilder assists with making links

func (*LinkBuilder) AddParam

func (lb *LinkBuilder) AddParam(name string, expression any) *LinkBuilder

AddParam adds a link param, expression is a OpenAPI runtime expressions (see https://swagger.io/docs/specification/links/)

func (*LinkBuilder) Description

func (lb *LinkBuilder) Description(description string) *LinkBuilder

Description sets the description of the link

func (*LinkBuilder) OperationID

func (lb *LinkBuilder) OperationID(operationID string) *LinkBuilder

Set the OperationID of this link.

func (*LinkBuilder) OperationRef

func (lb *LinkBuilder) OperationRef(operationRef string) *LinkBuilder

OperationRef sets the OperationRef for the link.

func (*LinkBuilder) RequestBody

func (lb *LinkBuilder) RequestBody(expression any) *LinkBuilder

RequestBody sets the link request body, expression is an OpenAPI run time expression (see https://swagger.io/docs/specification/links/)

func (*LinkBuilder) Server

func (lb *LinkBuilder) Server() *ServerBuilder

Server adds a server for the link

type MediaType

type MediaType struct {
	// Schema defining the content of the request, response, or parameter.
	Schema *Schema `yaml:"schema,omitempty"`

	// Example of the media type. The example object SHOULD be in the correct
	// format as specified by the media type. The example field is mutually
	// exclusive of the examples field. Furthermore, if referencing a schema which
	// contains an example, the example value SHALL override the example provided
	// by the schema.
	Example any `yaml:"example,omitempty"`

	// Examples of the media type. Each example object SHOULD match the media type
	// and specified schema if present. The examples field is mutually exclusive
	// of the example field. Furthermore, if referencing a schema which contains
	// an example, the examples value SHALL override the example provided by the
	// schema.
	Examples map[string]*Example `yaml:"examples,omitempty"`

	// Encoding is a map between a property name and its encoding information. The
	// key, being the property name, MUST exist in the schema as a property. The
	// encoding object SHALL only apply to requestBody objects when the media type
	// is multipart or application/x-www-form-urlencoded.
	Encoding map[string]*Encoding `yaml:"encoding,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

MediaType object provides schema and examples for the media type identified by its key.

application/json:
  schema:
    $ref: "#/components/schemas/Pet"
  examples:
    cat:
      summary: An example of a cat
      value:
        name: Fluffy
        petType: Cat
        color: White
        gender: male
        breed: Persian

func (*MediaType) MarshalJSON

func (m *MediaType) MarshalJSON() ([]byte, error)

type MediaTypeBuilder

type MediaTypeBuilder struct {
	// contains filtered or unexported fields
}

func (*MediaTypeBuilder) AddExample

func (mtb *MediaTypeBuilder) AddExample(name string) *ExampleBuilder

AddExample adds an example with a name.

func (*MediaTypeBuilder) Example

func (mtb *MediaTypeBuilder) Example(example string) *MediaTypeBuilder

Example sets the example for this media type

func (*MediaTypeBuilder) Schema

func (mtb *MediaTypeBuilder) Schema(f any)

Schema overrides the schema with the type f

type ModelValidator

type ModelValidator struct {
	// contains filtered or unexported fields
}

ModelValidator is a utility for validating e.g. JSON loaded data against a Go struct model. It is not goroutine-safe and should not be used in HTTP handlers! Schemas are generated on-the-fly on first use and re-used on subsequent calls. This utility can be used to easily validate data outside of the normal request/response flow, for example on application startup:

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}

func NewModelValidator

func NewModelValidator() *ModelValidator

NewModelValidator creates a new model validator with all the components it needs to create schemas, validate them, and return any errors.

func (*ModelValidator) Validate

func (v *ModelValidator) Validate(typ reflect.Type, value any) []error

Validate the inputs. The type should be the Go struct with validation field tags and the value should be e.g. JSON loaded into an `any`. A list of errors is returned if validation failed, otherwise `nil`.

type MyExample struct {
	Name string `json:"name" maxLength:"5"`
	Age int `json:"age" minimum:"25"`
}

var value any
json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &value)

validator := ModelValidator()
errs := validator.Validate(reflect.TypeOf(MyExample{}), value)
if errs != nil {
	fmt.Println("Validation error", errs)
}

type OAuth2Builder

type OAuth2Builder struct {
	// contains filtered or unexported fields
}

OAuth2Builder helps build OAuth2

func (*OAuth2Builder) AuthorizationCode

func (ob *OAuth2Builder) AuthorizationCode() *OAuthFlowBuilder

AuthorizationCode sets the AuthorizationCode flow

func (*OAuth2Builder) ClientCredentials

func (ob *OAuth2Builder) ClientCredentials() *OAuthFlowBuilder

ClientCredentials sets the ClientCredentials flow

func (*OAuth2Builder) Implicit

func (ob *OAuth2Builder) Implicit() *OAuthFlowBuilder

Implicit sets the Implicit flow

func (*OAuth2Builder) Password

func (ob *OAuth2Builder) Password() *OAuthFlowBuilder

Password sets the Password flow

type OAuthFlow

type OAuthFlow struct {
	// AuthorizationURL is REQUIRED for `implicit` and `authorizationCode` flows.
	// The authorization URL to be used for this flow. This MUST be in the form of
	// a URL. The OAuth2 standard requires the use of TLS.
	AuthorizationURL string `yaml:"authorizationUrl,omitempty"`

	// TokenURL is REQUIRED. The token URL to be used for this flow. This MUST be
	// in the form of a URL. The OAuth2 standard requires the use of TLS.
	TokenURL string `yaml:"tokenUrl"`

	// RefreshURL is the URL to be used for obtaining refresh tokens. This MUST be
	// in the form of a URL. The OAuth2 standard requires the use of TLS.
	RefreshURL string `yaml:"refreshUrl,omitempty"`

	// Scopes are REQUIRED. The available scopes for the OAuth2 security scheme. A
	// map between the scope name and a short description for it. The map MAY be
	// empty.
	Scopes map[string]string `yaml:"scopes"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

OAuthFlow stores configuration details for a supported OAuth Flow.

type: oauth2
flows:
  implicit:
    authorizationUrl: https://example.com/api/oauth/dialog
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets
  authorizationCode:
    authorizationUrl: https://example.com/api/oauth/dialog
    tokenUrl: https://example.com/api/oauth/token
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets

func (*OAuthFlow) MarshalJSON

func (o *OAuthFlow) MarshalJSON() ([]byte, error)

type OAuthFlowBuilder

type OAuthFlowBuilder struct {
	// contains filtered or unexported fields
}

OAuthFlowBuilder helps build a oauth flow

func (*OAuthFlowBuilder) AuthorizationURL

func (b *OAuthFlowBuilder) AuthorizationURL(url string) *OAuthFlowBuilder

AuthorizationURL sets the authorization url for the flow

func (*OAuthFlowBuilder) RefreshURL

func (b *OAuthFlowBuilder) RefreshURL(url string) *OAuthFlowBuilder

RefreshURL sets the refresh url for the flow

func (*OAuthFlowBuilder) Scopes

func (b *OAuthFlowBuilder) Scopes(scopes map[string]string) *OAuthFlowBuilder

Scopes sets the scope for the flow

func (*OAuthFlowBuilder) TokenURL

func (b *OAuthFlowBuilder) TokenURL(url string) *OAuthFlowBuilder

TokenURL sets the token url for the flow

type OAuthFlows

type OAuthFlows struct {
	// Implicit is the configuration for the OAuth Implicit flow.
	Implicit *OAuthFlow `yaml:"implicit,omitempty"`

	// Password is the configuration for the OAuth Resource Owner Password flow.
	Password *OAuthFlow `yaml:"password,omitempty"`

	// ClientCredentials is the configuration for the OAuth Client Credentials
	// flow. Previously called application in OpenAPI 2.0.
	ClientCredentials *OAuthFlow `yaml:"clientCredentials,omitempty"`

	// AuthorizationCode is the configuration for the OAuth Authorization Code
	// flow. Previously called accessCode in OpenAPI 2.0.
	AuthorizationCode *OAuthFlow `yaml:"authorizationCode,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

OAuthFlows allows configuration of the supported OAuth Flows.

func (*OAuthFlows) MarshalJSON

func (o *OAuthFlows) MarshalJSON() ([]byte, error)

type OpenAPI

type OpenAPI struct {
	// OpenAPI is REQUIRED. This string MUST be the version number of the OpenAPI
	// Specification that the OpenAPI document uses. The openapi field SHOULD be
	// used by tooling to interpret the OpenAPI document. This is not related to
	// the API info.version string.
	OpenAPI string `yaml:"openapi"`

	// Info is REQUIRED. Provides metadata about the API. The metadata MAY be used
	// by tooling as required.
	Info *Info `yaml:"info"`

	// JSONSchemaDialect is the default value for the $schema keyword within Schema
	// Objects contained within this OAS document. This MUST be in the form of a
	// URI.
	JSONSchemaDialect string `yaml:"jsonSchemaDialect,omitempty"`

	// Servers is an array of Server Objects, which provide connectivity
	// information to a target server. If the servers property is not provided, or
	// is an empty array, the default value would be a Server Object with a url
	// value of /.
	Servers []*Server `yaml:"servers,omitempty"`

	// Paths are the available paths and operations for the API.
	Paths map[string]*PathItem `yaml:"paths,omitempty"`

	// Webhooks that MAY be received as part of this API and that the API consumer
	// MAY choose to implement. Closely related to the callbacks feature, this
	// section describes requests initiated other than by an API call, for example
	// by an out of band registration. The key name is a unique string to refer to
	// each webhook, while the (optionally referenced) Path Item Object describes
	// a request that may be initiated by the API provider and the expected
	// responses. An example is available.
	Webhooks map[string]*PathItem `yaml:"webhooks,omitempty"`

	// Components is an element to hold various schemas for the document.
	Components *Components `yaml:"components,omitempty"`

	// Security is a declaration of which security mechanisms can be used across
	// the API. The list of values includes alternative security requirement
	// objects that can be used. Only one of the security requirement objects need
	// to be satisfied to authorize a request. Individual operations can override
	// this definition. To make security optional, an empty security requirement
	// ({}) can be included in the array.
	Security []map[string][]string `yaml:"security,omitempty"`

	// Tags are a list of tags used by the document with additional metadata. The
	// order of the tags can be used to reflect on their order by the parsing
	// tools. Not all tags that are used by the Operation Object must be declared.
	// The tags that are not declared MAY be organized randomly or based on the
	// tools’ logic. Each tag name in the list MUST be unique.
	Tags []*Tag `yaml:"tags,omitempty"`

	// ExternalDocs is additional external documentation.
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`

	// OnAddOperation is called when an operation is added to the OpenAPI via
	// `AddOperation`. You may bypass this by directly writing to the `Paths`
	// map instead.
	OnAddOperation []AddOpFunc `yaml:"-"`
}

OpenAPI is the root object of the OpenAPI document.

func (*OpenAPI) AddOperation

func (o *OpenAPI) AddOperation(op *Operation)

AddOperation adds an operation to the OpenAPI. This is the preferred way to add operations to the OpenAPI, as it will ensure that the operation is properly added to the Paths map, and will call any registered OnAddOperation functions.

func (OpenAPI) Downgrade

func (o OpenAPI) Downgrade() ([]byte, error)

Downgrade converts this OpenAPI 3.1 spec to OpenAPI 3.0.3, returning the JSON []byte representation of the downgraded spec. This mostly exists to provide an alternative spec for tools which are not yet 3.1 compatible.

It reverses the changes documented at: https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0

func (*OpenAPI) DowngradeYAML

func (o *OpenAPI) DowngradeYAML() ([]byte, error)

DowngradeYAML converts this OpenAPI 3.1 spec to OpenAPI 3.0.3, returning the YAML []byte representation of the downgraded spec.

func (*OpenAPI) MarshalJSON

func (o *OpenAPI) MarshalJSON() ([]byte, error)

func (*OpenAPI) YAML

func (o *OpenAPI) YAML() ([]byte, error)

YAML returns the OpenAPI represented as YAML without needing to include a library to serialize YAML.

type Operation

type Operation struct {
	// Method is the HTTP method for this operation
	Method string `yaml:"-"`

	// Path is the URL path for this operation
	Path string `yaml:"-"`

	// Tags is a list of tags for API documentation control. Tags can be used for
	// logical grouping of operations by resources or any other qualifier.
	Tags []string `yaml:"tags,omitempty"`

	// Summary is a short summary of what the operation does.
	Summary string `yaml:"summary,omitempty"`

	// Description is a verbose explanation of the operation behavior. CommonMark
	// syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// ExternalDocs describes additional external documentation for this
	// operation.
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`

	// OperationID is a unique string used to identify the operation. The id MUST
	// be unique among all operations described in the API. The operationId value
	// is case-sensitive. Tools and libraries MAY use the operationId to uniquely
	// identify an operation, therefore, it is RECOMMENDED to follow common
	// programming naming conventions.
	OperationID string `yaml:"operationId,omitempty"`

	// Parameters is a list of parameters that are applicable for this operation.
	// If a parameter is already defined at the Path Item, the new definition will
	// override it but can never remove it. The list MUST NOT include duplicated
	// parameters. A unique parameter is defined by a combination of a name and
	// location. The list can use the Reference Object to link to parameters that
	// are defined at the OpenAPI Object’s components/parameters.
	Parameters []*Param `yaml:"parameters,omitempty"`

	// RequestBody applicable for this operation. The requestBody is fully
	// supported in HTTP methods where the HTTP 1.1 specification [RFC7231] has
	// explicitly defined semantics for request bodies. In other cases where the
	// HTTP spec is vague (such as GET, HEAD and DELETE), requestBody is permitted
	// but does not have well-defined semantics and SHOULD be avoided if possible.
	RequestBody *RequestBody `yaml:"requestBody,omitempty"`

	// Responses is the list of possible responses as they are returned from
	// executing this operation.
	Responses map[string]*Response `yaml:"responses,omitempty"`

	// Callbacks is a map of possible out-of band callbacks related to the parent
	// operation. The key is a unique identifier for the Callback Object. Each
	// value in the map is a Callback Object that describes a request that may be
	// initiated by the API provider and the expected responses.
	Callbacks map[string]map[string]*PathItem `yaml:"callbacks,omitempty"`

	// Deprecated declares this operation to be deprecated. Consumers SHOULD
	// refrain from usage of the declared operation. Default value is false.
	Deprecated bool `yaml:"deprecated,omitempty"`

	// Security is a declaration of which security mechanisms can be used for this
	// operation. The list of values includes alternative security requirement
	// objects that can be used. Only one of the security requirement objects need
	// to be satisfied to authorize a request. To make security optional, an empty
	// security requirement ({}) can be included in the array. This definition
	// overrides any declared top-level security. To remove a top-level security
	// declaration, an empty array can be used.
	Security []map[string][]string `yaml:"security,omitempty"`

	// Servers is an alternative server array to service this operation. If an
	// alternative server object is specified at the Path Item Object or Root
	// level, it will be overridden by this value.
	Servers []*Server `yaml:"servers,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Operation describes a single API operation on a path.

tags:
- pet
summary: Updates a pet in the store with form data
operationId: updatePetWithForm
parameters:
- name: petId
  in: path
  description: ID of pet that needs to be updated
  required: true
  schema:
    type: string
requestBody:
  content:
    'application/x-www-form-urlencoded':
      schema:
       type: object
       properties:
          name:
            description: Updated name of the pet
            type: string
          status:
            description: Updated status of the pet
            type: string
       required:
         - status
responses:
  '200':
    description: Pet updated.
    content:
      'application/json': {}
      'application/xml': {}
  '405':
    description: Method Not Allowed
    content:
      'application/json': {}
      'application/xml': {}
security:
- petstore_auth:
  - write:pets
  - read:pets

func (*Operation) MarshalJSON

func (o *Operation) MarshalJSON() ([]byte, error)

type OperationBuilder

type OperationBuilder struct {
	// contains filtered or unexported fields
}

OperationBuilder assists in building an openapi.Operation

func (*OperationBuilder) Callback

func (ob *OperationBuilder) Callback(event string, op *Operation) *OperationBuilder

Callback adds a callback.

func (*OperationBuilder) Description

func (ob *OperationBuilder) Description(description string) *OperationBuilder

Description sets the description

func (*OperationBuilder) Request

func (ob *OperationBuilder) Request() *RequestBuilder

Request returns a RequestBuilder which helps build a request

func (*OperationBuilder) Response

func (ob *OperationBuilder) Response(status int) *ResponseBuilder

Response adds a response with a status code.

func (*OperationBuilder) Security

func (ob *OperationBuilder) Security(securitySchema string, params []string) *OperationBuilder

Security sets the security for this operation

func (*OperationBuilder) Server

func (ob *OperationBuilder) Server() *ServerBuilder

Server adds a server for this operation.

func (*OperationBuilder) Summary

func (ob *OperationBuilder) Summary(summary string) *OperationBuilder

Summary sets the summary.

func (*OperationBuilder) Tag

Tag adds a tag

type Param

type Param struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Name is REQUIRED. The name of the parameter. Parameter names are case
	// sensitive.
	//
	//   - If in is "path", the name field MUST correspond to a template expression
	//     occurring within the path field in the Paths Object. See Path Templating
	//     for further information.
	//
	//   - If in is "header" and the name field is "Accept", "Content-Type" or
	//     "Authorization", the parameter definition SHALL be ignored.
	//
	//   - For all other cases, the name corresponds to the parameter name used by
	//     the in property.
	Name string `yaml:"name,omitempty"`

	// In is REQUIRED. The location of the parameter. Possible values are "query",
	// "header", "path" or "cookie".
	In string `yaml:"in,omitempty"`

	// Description of the parameter. This could contain examples of use.
	// CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Required determines whether this parameter is mandatory. If the parameter
	// location is "path", this property is REQUIRED and its value MUST be true.
	// Otherwise, the property MAY be included and its default value is false.
	Required bool `yaml:"required,omitempty"`

	// Deprecated specifies that a parameter is deprecated and SHOULD be
	// transitioned out of usage. Default value is false.
	Deprecated bool `yaml:"deprecated,omitempty"`

	// AllowEmptyValue sets the ability to pass empty-valued parameters. This is
	// valid only for query parameters and allows sending a parameter with an
	// empty value. Default value is false. If style is used, and if behavior is
	// n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored.
	// Use of this property is NOT RECOMMENDED, as it is likely to be removed in a
	// later revision.
	AllowEmptyValue bool `yaml:"allowEmptyValue,omitempty"`

	// Style describes how the parameter value will be serialized depending on the
	// type of the parameter value. Default values (based on value of in): for
	// query - form; for path - simple; for header - simple; for cookie - form.
	Style string `yaml:"style,omitempty"`

	// Explode, when true, makes parameter values of type array or object generate
	// separate parameters for each value of the array or key-value pair of the
	// map. For other types of parameters this property has no effect. When style
	// is form, the default value is true. For all other styles, the default value
	// is false.
	Explode *bool `yaml:"explode,omitempty"`

	// AllowReserved determines whether the parameter value SHOULD allow reserved
	// characters, as defined by [RFC3986] :/?#[]@!$&'()*+,;= to be included
	// without percent-encoding. This property only applies to parameters with an
	// in value of query. The default value is false.
	AllowReserved bool `yaml:"allowReserved,omitempty"`

	// Schema defining the type used for the parameter.
	Schema *Schema `yaml:"schema,omitempty"`

	// Example of the parameter’s potential value. The example SHOULD match the
	// specified schema and encoding properties if present. The example field is
	// mutually exclusive of the examples field. Furthermore, if referencing a
	// schema that contains an example, the example value SHALL override the
	// example provided by the schema. To represent examples of media types that
	// cannot naturally be represented in JSON or YAML, a string value can contain
	// the example with escaping where necessary.
	Example any `yaml:"example,omitempty"`

	// Examples of the parameter’s potential value. Each example SHOULD contain a
	// value in the correct format as specified in the parameter encoding. The
	// examples field is mutually exclusive of the example field. Furthermore, if
	// referencing a schema that contains an example, the examples value SHALL
	// override the example provided by the schema.
	Examples map[string]*Example `yaml:"examples,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Param Describes a single operation parameter.

A unique parameter is defined by a combination of a name and location.

name: username
in: path
description: username to fetch
required: true
schema:
  type: string

func (*Param) MarshalJSON

func (p *Param) MarshalJSON() ([]byte, error)

type ParamBuilder

type ParamBuilder struct {
	// contains filtered or unexported fields
}

ParamBuilder helps with building an openapi.Param

func (*ParamBuilder) AddExample

func (pb *ParamBuilder) AddExample(name string) *ExampleBuilder

AddExample adds an example to a list of examples.

func (*ParamBuilder) Description

func (pb *ParamBuilder) Description(description string) *ParamBuilder

Description sets the description of the param

func (*ParamBuilder) Example

func (pb *ParamBuilder) Example(example string) *ParamBuilder

Example sets the example for the param. If you want to add multiple examples, call AddExample() instead.

func (*ParamBuilder) Explode

func (pb *ParamBuilder) Explode(explode bool) *ParamBuilder

Explode explodes

func (*ParamBuilder) In

func (pb *ParamBuilder) In(in string) *ParamBuilder

In can be "query", "path" or "cookie". This should already be set when creating the param and is only here for a manual override.

func (*ParamBuilder) Required

func (pb *ParamBuilder) Required(required bool) *ParamBuilder

Required sets the param as required

func (*ParamBuilder) Style

func (pb *ParamBuilder) Style(style string) *ParamBuilder

Style sets the style of the param. See https://swagger.io/docs/specification/serialization/

type PathBuffer

type PathBuffer struct {
	// contains filtered or unexported fields
}

PathBuffer is a low-allocation helper for building a path string like `foo.bar.baz`. It is not goroutine-safe. Combined with `sync.Pool` it can result in zero allocations, and is used for validation. It is significantly better than `strings.Builder` and `bytes.Buffer` for this use case.

Path buffers can be converted to strings for use in responses or printing using either the `pb.String()` or `pb.With("field")` methods.

pb := NewPathBuffer([]byte{}, 0)
pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]
pb.Push("bar")  // foo[1].bar
pb.Pop()        // foo[1]
pb.Pop()        // foo

func NewPathBuffer

func NewPathBuffer(buf []byte, offset int) *PathBuffer

NewPathBuffer creates a new path buffer given an existing byte slice. Tip: using `sync.Pool` can significantly reduce buffer allocations.

pb := NewPathBuffer([]byte{}, 0)
pb.Push("foo")

func (*PathBuffer) Bytes

func (b *PathBuffer) Bytes() []byte

Bytes returns the underlying slice of bytes of the path.

func (*PathBuffer) Len

func (b *PathBuffer) Len() int

Len returns the length of the current path.

func (*PathBuffer) Pop

func (b *PathBuffer) Pop()

Pop the latest entry off the path.

pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]
pb.Push("bar")  // foo[1].bar
pb.Pop()        // foo[1]
pb.Pop()        // foo

func (*PathBuffer) Push

func (b *PathBuffer) Push(s string)

Push an entry onto the path, adding a `.` separator as needed.

pb.Push("foo") // foo
pb.Push("bar") // foo.bar

func (*PathBuffer) PushIndex

func (b *PathBuffer) PushIndex(i int)

PushIndex pushes an entry onto the path surrounded by `[` and `]`.

pb.Push("foo")  // foo
pb.PushIndex(1) // foo[1]

func (*PathBuffer) Reset

func (b *PathBuffer) Reset()

Reset the path buffer to empty, keeping and reusing the underlying bytes.

func (*PathBuffer) String

func (b *PathBuffer) String() string

String converts the path buffer to a string.

func (*PathBuffer) With

func (b *PathBuffer) With(s string) string

With is shorthand for push, convert to string, and pop. This is useful when you want the location of a field given a path buffer as a prefix.

pb.Push("foo")
pb.With("bar") // returns foo.bar

type PathItem

type PathItem struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Summary is an optional, string summary, intended to apply to all operations
	// in this path.
	Summary string `yaml:"summary,omitempty"`

	// Description is an optional, string description, intended to apply to all
	// operations in this path. CommonMark syntax MAY be used for rich text
	// representation.
	Description string `yaml:"description,omitempty"`

	// Get is a definition of a GET operation on this path.
	Get *Operation `yaml:"get,omitempty"`

	// Put is a definition of a PUT operation on this path.
	Put *Operation `yaml:"put,omitempty"`

	// Post is a definition of a POST operation on this path.
	Post *Operation `yaml:"post,omitempty"`

	// Delete is a definition of a DELETE operation on this path.
	Delete *Operation `yaml:"delete,omitempty"`

	// Options is a definition of a OPTIONS operation on this path.
	Options *Operation `yaml:"options,omitempty"`

	// Head is a definition of a HEAD operation on this path.
	Head *Operation `yaml:"head,omitempty"`

	// Patch is a definition of a PATCH operation on this path.
	Patch *Operation `yaml:"patch,omitempty"`

	// Trace is a definition of a TRACE operation on this path.
	Trace *Operation `yaml:"trace,omitempty"`

	// Servers is an alternative server array to service all operations in this
	// path.
	Servers []*Server `yaml:"servers,omitempty"`

	// Parameters is a list of parameters that are applicable for all the
	// operations described under this path. These parameters can be overridden at
	// the operation level, but cannot be removed there. The list MUST NOT include
	// duplicated parameters. A unique parameter is defined by a combination of a
	// name and location. The list can use the Reference Object to link to
	// parameters that are defined at the OpenAPI Object’s components/parameters.
	Parameters []*Param `yaml:"parameters,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

PathItem describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.

get:
  description: Returns pets based on ID
  summary: Find pets by ID
  operationId: getPetsById
  responses:
    '200':
      description: pet response
      content:
        '*/*' :
          schema:
            type: array
            items:
              $ref: '#/components/schemas/Pet'
    default:
      description: error payload
      content:
        'text/html':
          schema:
            $ref: '#/components/schemas/ErrorModel'
parameters:
- name: id
  in: path
  description: ID of pet to use
  required: true
  schema:
    type: array
    items:
      type: string
  style: simple

func (*PathItem) MarshalJSON

func (p *PathItem) MarshalJSON() ([]byte, error)

type Registry

type Registry interface {
	Schema(t reflect.Type, allowRef bool, hint string) *Schema
	SchemaFromRef(ref string) *Schema
	TypeFromRef(ref string) reflect.Type
	Map() map[string]*Schema
	RegisterTypeAlias(t reflect.Type, alias reflect.Type)
}

Registry creates and stores schemas and their references, and supports marshalling to JSON/YAML for use as an OpenAPI #/components/schemas object. Behavior is implementation-dependent, but the design allows for recursive schemas to exist while being flexible enough to support other use cases like only inline objects (no refs) or always using refs for structs.

func NewMapRegistry

func NewMapRegistry(prefix string, namer func(t reflect.Type, hint string) string) Registry

NewMapRegistry creates a new registry that stores schemas in a map and returns references to them using the given prefix.

type RequestBody

type RequestBody struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Description of the request body. This could contain examples of use.
	// CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Content is REQUIRED. The content of the request body. The key is a media
	// type or media type range and the value describes it. For requests that
	// match multiple keys, only the most specific key is applicable. e.g.
	// text/plain overrides text/*
	Content map[string]*MediaType `yaml:"content"`

	// Required Determines if the request body is required in the request.
	// Defaults to false.
	Required bool `yaml:"required,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

RequestBody describes a single request body.

description: user to add to the system
content:
  'application/json':
    schema:
      $ref: '#/components/schemas/User'
    examples:
      user:
        summary: User Example
        externalValue: 'https://foo.bar/examples/user-example.json'

func (*RequestBody) MarshalJSON

func (r *RequestBody) MarshalJSON() ([]byte, error)

type RequestBodyBuilder

type RequestBodyBuilder struct {
	// contains filtered or unexported fields
}

func (*RequestBodyBuilder) AddExample

func (rbb *RequestBodyBuilder) AddExample(example string) *ExampleBuilder

AddExample adds an example for the body

func (*RequestBodyBuilder) Description

func (rbb *RequestBodyBuilder) Description(description string) *RequestBodyBuilder

Description sets the Description for the RequestBody

func (*RequestBodyBuilder) Example

func (rbb *RequestBodyBuilder) Example(example string) *RequestBodyBuilder

Example sets the example for the body

func (*RequestBodyBuilder) Required

func (rbb *RequestBodyBuilder) Required(required bool) *RequestBodyBuilder

Required makes the Body required for the Request. By default when you call Body() it is already set to true

type RequestBuilder

type RequestBuilder struct {
	// contains filtered or unexported fields
}

RequestBuilder helps build a Request

func (*RequestBuilder) Body

func (rb *RequestBuilder) Body(f any) *RequestBodyBuilder

Body sets the RequestBody

func (*RequestBuilder) ContentType

func (rb *RequestBuilder) ContentType(contentType string) *RequestBuilder

ContentType sets the content type of the Request for the next Body() call

func (*RequestBuilder) CookieParam

func (rb *RequestBuilder) CookieParam(name string, f any) *ParamBuilder

CookieParam adds a cookie param

func (*RequestBuilder) DefaultContentType

func (rb *RequestBuilder) DefaultContentType(contentType string) *RequestBuilder

DefaultContentType sets the content type for all Body() calls

func (*RequestBuilder) Param

func (rb *RequestBuilder) Param(in string, name string, f any) *ParamBuilder

Param adds a param. in can be "path", "query", or "cookie". See helper functions QueryParam(), PathParam() and CookieParam() for a shorthand version

func (*RequestBuilder) PathParam

func (rb *RequestBuilder) PathParam(name string, f any) *ParamBuilder

PathParam adds a path param

func (*RequestBuilder) QueryParam

func (rb *RequestBuilder) QueryParam(name string, f any) *ParamBuilder

QueryParam adds a query param

type Response

type Response struct {
	// Ref is a reference to another example. This field is mutually exclusive
	// with the other fields.
	Ref string `yaml:"$ref,omitempty"`

	// Description is REQUIRED. A description of the response. CommonMark syntax
	// MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Headers maps a header name to its definition. [RFC7230] states header names
	// are case insensitive. If a response header is defined with the name
	// "Content-Type", it SHALL be ignored.
	Headers map[string]*Param `yaml:"headers,omitempty"`

	// Content is a map containing descriptions of potential response payloads.
	// The key is a media type or media type range and the value describes it. For
	// responses that match multiple keys, only the most specific key is
	// applicable. e.g. text/plain overrides text/*
	Content map[string]*MediaType `yaml:"content,omitempty"`

	// Links is a map of operations links that can be followed from the response.
	// The key of the map is a short name for the link, following the naming
	// constraints of the names for Component Objects.
	Links map[string]*Link `yaml:"links,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Response describes a single response from an API Operation, including design-time, static links to operations based on the response.

description: A complex object array response
content:
  application/json:
    schema:
      type: array
      items:
        $ref: '#/components/schemas/VeryComplexType'

func (*Response) MarshalJSON

func (r *Response) MarshalJSON() ([]byte, error)

type ResponseBuilder

type ResponseBuilder struct {
	// contains filtered or unexported fields
}

func (*ResponseBuilder) Body

func (rb *ResponseBuilder) Body(f any) *MediaTypeBuilder

Body adds a body. f is the type that is used for the body's schema. f can be a struct, slice, map, or a basic type. For basic types, you can use our helper methods such as openapi.IntType, openapi.StringType, openapi.UintType, etc. (see types.go for all basic types.)

func (*ResponseBuilder) ContentType

func (rb *ResponseBuilder) ContentType(contentType string) *ResponseBuilder

ContentType applies this content type to the next Body() call. This only applies to the next Body() call and any subsequent calls to Body() will default to DefaultContentType(). If you want to change the default content type for all Body() calls, call DefaultContentType() then call Body() without using ContentType()

func (*ResponseBuilder) DefaultContentType

func (rb *ResponseBuilder) DefaultContentType(contentType string) *ResponseBuilder

DefaultContentType sets the default content type of the Response. By default, the content type is application/json

func (*ResponseBuilder) Header

func (rb *ResponseBuilder) Header(name string, f any) *ParamBuilder

Header adds a Header.

func (rb *ResponseBuilder) Link(name string) *LinkBuilder

Link adds a link to the response.

type Schema

type Schema struct {
	Type                 string              `yaml:"type,omitempty"`
	Nullable             bool                `yaml:"-"`
	Title                string              `yaml:"title,omitempty"`
	Description          string              `yaml:"description,omitempty"`
	Ref                  string              `yaml:"$ref,omitempty"`
	Format               string              `yaml:"format,omitempty"`
	ContentEncoding      string              `yaml:"contentEncoding,omitempty"`
	Default              any                 `yaml:"default,omitempty"`
	Examples             []any               `yaml:"examples,omitempty"`
	Items                *Schema             `yaml:"items,omitempty"`
	AdditionalProperties any                 `yaml:"additionalProperties,omitempty"`
	Properties           map[string]*Schema  `yaml:"properties,omitempty"`
	Enum                 []any               `yaml:"enum,omitempty"`
	Minimum              *float64            `yaml:"minimum,omitempty"`
	ExclusiveMinimum     *float64            `yaml:"exclusiveMinimum,omitempty"`
	Maximum              *float64            `yaml:"maximum,omitempty"`
	ExclusiveMaximum     *float64            `yaml:"exclusiveMaximum,omitempty"`
	MultipleOf           *float64            `yaml:"multipleOf,omitempty"`
	MinLength            *int                `yaml:"minLength,omitempty"`
	MaxLength            *int                `yaml:"maxLength,omitempty"`
	Pattern              string              `yaml:"pattern,omitempty"`
	PatternDescription   string              `yaml:"patternDescription,omitempty"`
	MinItems             *int                `yaml:"minItems,omitempty"`
	MaxItems             *int                `yaml:"maxItems,omitempty"`
	UniqueItems          bool                `yaml:"uniqueItems,omitempty"`
	Required             []string            `yaml:"required,omitempty"`
	MinProperties        *int                `yaml:"minProperties,omitempty"`
	MaxProperties        *int                `yaml:"maxProperties,omitempty"`
	ReadOnly             bool                `yaml:"readOnly,omitempty"`
	WriteOnly            bool                `yaml:"writeOnly,omitempty"`
	Deprecated           bool                `yaml:"deprecated,omitempty"`
	Extensions           map[string]any      `yaml:",inline"`
	DependentRequired    map[string][]string `yaml:"dependentRequired,omitempty"`

	OneOf []*Schema `yaml:"oneOf,omitempty"`
	AnyOf []*Schema `yaml:"anyOf,omitempty"`
	AllOf []*Schema `yaml:"allOf,omitempty"`
	Not   *Schema   `yaml:"not,omitempty"`
	// contains filtered or unexported fields
}

Schema represents a JSON Schema compatible with OpenAPI 3.1. It is extensible with your own custom properties. It supports a subset of the full JSON Schema spec, designed specifically for use with Go structs and to enable fast zero or near-zero allocation happy-path validation for incoming requests.

Typically you will use a registry and `openapi.SchemaFromType` to generate schemas for your types. You can then use `openapi.Validate` to validate incoming requests.

// Create a registry and register a type.
registry := openapi.NewMapRegistry("#/prefix", openapi.DefaultSchemaNamer)
schema := openapi.SchemaFromType(registry, reflect.TypeOf(MyType{}))

Note that the registry may create references for your types.

func SchemaFromField

func SchemaFromField(registry Registry, f reflect.StructField, hint string) *Schema

SchemaFromField generates a schema for a given struct field. If the field is a struct (or slice/map of structs) then the registry is used to potentially get a reference to that type.

This is used by `openapi.SchemaFromType` when it encounters a struct, and is used to generate schemas for path/query/header parameters.

func SchemaFromType

func SchemaFromType(r Registry, t reflect.Type) *Schema

SchemaFromType returns a schema for a given type, using the registry to possibly create references for nested structs. The schema that is returned can then be passed to `openapi.Validate` to efficiently validate incoming requests.

// Create a registry and register a type.
registry := openapi.NewMapRegistry("#/prefix", openapi.DefaultSchemaNamer)
schema := openapi.SchemaFromType(registry, reflect.TypeOf(MyType{}))

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON marshals the schema into JSON, respecting the `Extensions` map to marshal extensions inline.

func (*Schema) PrecomputeMessages

func (s *Schema) PrecomputeMessages()

PrecomputeMessages tries to precompute as many validation error messages as possible so that new strings aren't allocated during request validation.

type SchemaProvider

type SchemaProvider interface {
	Schema(r Registry) *Schema
}

SchemaProvider is an interface that can be implemented by types to provide a custom schema for themselves, overriding the built-in schema generation. This can be used by custom types with their own special serialization rules.

type SecurityScheme

type SecurityScheme struct {
	// Type is REQUIRED. The type of the security scheme. Valid values are
	// "apiKey", "http", "mutualTLS", "oauth2", "openIdConnect".
	Type string `yaml:"type"`

	// Description for security scheme. CommonMark syntax MAY be used for rich
	// text representation.
	Description string `yaml:"description,omitempty"`

	// Name is REQUIRED. The name of the header, query or cookie parameter to be
	// used.
	Name string `yaml:"name,omitempty"`

	// In is REQUIRED. The location of the API key. Valid values are "query",
	// "header" or "cookie".
	In string `yaml:"in,omitempty"`

	// Scheme is REQUIRED. The name of the HTTP Authorization scheme to be used in
	// the Authorization header as defined in [RFC7235]. The values used SHOULD be
	// registered in the IANA Authentication Scheme registry.
	Scheme string `yaml:"scheme,omitempty"`

	// BearerFormat is a hint to the client to identify how the bearer token is
	// formatted. Bearer tokens are usually generated by an authorization server,
	// so this information is primarily for documentation purposes.
	BearerFormat string `yaml:"bearerFormat,omitempty"`

	// Flows is REQUIRED. An object containing configuration information for the
	// flow types supported.
	Flows *OAuthFlows `yaml:"flows,omitempty"`

	// OpenIDConnectURL is REQUIRED. OpenId Connect URL to discover OAuth2
	// configuration values. This MUST be in the form of a URL. The OpenID Connect
	// standard requires the use of TLS.
	OpenIDConnectURL string `yaml:"openIdConnectUrl,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

SecurityScheme defines a security scheme that can be used by the operations.

Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2’s common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749], and OpenID Connect Discovery. Please note that as of 2020, the implicit flow is about to be deprecated by OAuth 2.0 Security Best Current Practice. Recommended for most use case is Authorization Code Grant flow with PKCE.

type: http
scheme: bearer
bearerFormat: JWT

func (*SecurityScheme) MarshalJSON

func (s *SecurityScheme) MarshalJSON() ([]byte, error)

type Server

type Server struct {
	// URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
	URL string `yaml:"url"`

	// Description of the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Variables map between a variable name and its value. The value is used for substitution in the server’s URL template.
	Variables map[string]*ServerVariable `yaml:"variables,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Server URL, optionally with variables.

servers:
- url: https://development.gigantic-server.com/v1
  description: Development server
- url: https://staging.gigantic-server.com/v1
  description: Staging server
- url: https://api.gigantic-server.com/v1
  description: Production server

func (*Server) MarshalJSON

func (s *Server) MarshalJSON() ([]byte, error)

type ServerBuilder

type ServerBuilder struct {
	// contains filtered or unexported fields
}

ServerBuilder helps with building a Server

func (*ServerBuilder) AddVariable

func (sb *ServerBuilder) AddVariable(name string) *ServerVariableBuilder

AddVariable adds a variable to the server.

func (*ServerBuilder) Description

func (sb *ServerBuilder) Description(description string) *ServerBuilder

Description sets the server description

func (*ServerBuilder) URL

func (sb *ServerBuilder) URL(url string) *ServerBuilder

URL sets the server URL

type ServerVariable

type ServerVariable struct {
	// Enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty.
	Enum []string `yaml:"enum,omitempty"`

	// Default value to use for substitution, which SHALL be sent if an alternate value is not supplied.
	Default string `yaml:"default"`

	// Description for the server variable. CommonMark syntax MAY be used for rich text representation.
	Description string `yaml:"description,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

ServerVariable for server URL template substitution.

func (*ServerVariable) MarshalJSON

func (v *ServerVariable) MarshalJSON() ([]byte, error)

type ServerVariableBuilder

type ServerVariableBuilder struct {
	// contains filtered or unexported fields
}

ServerVariableBuilder helps build a server variable

func (*ServerVariableBuilder) Default

func (svb *ServerVariableBuilder) Default(value string) *ServerVariableBuilder

Default sets the default value for the variable

func (*ServerVariableBuilder) Description

func (svb *ServerVariableBuilder) Description(description string) *ServerVariableBuilder

Description sets the description for the variable

func (*ServerVariableBuilder) Enum

Enum sets the enum for the variable

type Tag

type Tag struct {
	// Name is REQUIRED. The name of the tag.
	Name string `yaml:"name"`

	// Description for the tag. CommonMark syntax MAY be used for rich text
	// representation.
	Description string `yaml:"description,omitempty"`

	// ExternalDocs is additional external documentation for this tag.
	ExternalDocs *ExternalDocs `yaml:"externalDocs,omitempty"`

	// Extensions (user-defined properties), if any. Values in this map will
	// be marshalled as siblings of the other properties above.
	Extensions map[string]any `yaml:",inline"`
}

Tag adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.

func (*Tag) MarshalJSON

func (t *Tag) MarshalJSON() ([]byte, error)

type ValidateMode

type ValidateMode int

ValidateMode describes the direction of validation (server -> client or client -> server). It impacts things like how read-only or write-only fields are handled.

const (
	// ModeReadFromServer is a read mode (response output) that may ignore or
	// reject write-only fields that are non-zero, as these write-only fields
	// are meant to be sent by the client.
	ModeReadFromServer ValidateMode = iota

	// ModeWriteToServer is a write mode (request input) that may ignore or
	// reject read-only fields that are non-zero, as these are owned by the
	// server and the client should not try to modify them.
	ModeWriteToServer
)

type ValidateResult

type ValidateResult struct {
	Errors []error
}

ValidateResult tracks validation errors. It is safe to use for multiple validations as long as `Reset()` is called between uses.

func (*ValidateResult) Add

func (r *ValidateResult) Add(path *PathBuffer, v any, msg string)

Add an error to the validation result at the given path and with the given value.

func (*ValidateResult) Addf

func (r *ValidateResult) Addf(path *PathBuffer, v any, format string, args ...any)

Addf adds an error to the validation result at the given path and with the given value, allowing for fmt.Printf-style formatting.

func (*ValidateResult) Reset

func (r *ValidateResult) Reset()

Reset the validation error so it can be used again.

Directories

Path Synopsis
examples
Package yaml implements a converter from JSON to YAML.
Package yaml implements a converter from JSON to YAML.

Jump to

Keyboard shortcuts

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