├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── go.mod
├── go.sum
├── spec
├── any.go
├── any_or_expressions.go
├── callback.go
├── callback_or_refable.go
├── components.go
├── contact.go
├── discriminator.go
├── doc.go
├── encoding.go
├── example.go
├── example_or_refable.go
├── expressions.go
├── external_docs.go
├── hack
│ ├── gen_x_or_array.go
│ └── gen_x_or_refable.go
├── header.go
├── header_or_refable.go
├── header_util.go
├── info.go
├── license.go
├── link.go
├── link_or_refable.go
├── media_type.go
├── oauth_flow.go
├── oauth_flows.go
├── openapi.go
├── operation.go
├── parameter.go
├── parameter_or_refable.go
├── parameter_util.go
├── paths.go
├── refable.go
├── refable_util.go
├── request_body.go
├── request_body_or_refable.go
├── request_body_util.go
├── response.go
├── response_or_refable.go
├── response_util.go
├── schema.go
├── schema_or_refable.go
├── schema_util.go
├── security_requirement.go
├── security_scheme.go
├── security_scheme_or_refable.go
├── security_scheme_util.go
├── server.go
├── server_util.go
├── server_variable.go
├── tag.go
├── testdata
│ ├── api-with-examples.yaml
│ ├── callback-example.yaml
│ ├── link-example.yaml
│ ├── petstore-expanded.yaml
│ ├── petstore.yaml
│ └── uspto.yaml
└── xml.go
└── util
├── marshal.go
├── merge.go
├── open.go
└── yaml_and_json.go
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, build with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:alpine3.8 AS builder
2 | WORKDIR /go/src/github.com/wzshiming/openapi/
3 | COPY . .
4 | RUN go install github.com/wzshiming/openapi/cmd/...
5 |
6 | FROM wzshiming/upx AS upx
7 | COPY --from=builder /go/bin/ /go/bin/
8 | RUN upx /go/bin/*
9 |
10 | FROM alpine:3.8
11 | RUN apk add -U --no-cache ca-certificates openssl tzdata
12 | COPY --from=upx /go/bin/ /usr/local/bin/
13 |
14 | EXPOSE 9000
15 |
16 | CMD openapi
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 wzshiming
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OpenAPI
2 |
3 | [](https://godoc.org/github.com/wzshiming/openapi)
4 | [](https://github.com/wzshiming/openapi/blob/master/LICENSE)
5 |
6 | The object model for [OpenAPI specification documents](https://github.com/OAI/OpenAPI-Specification)
7 |
8 | UI move to [github.com/wzshiming/openapiui](https://github.com/wzshiming/openapiui)
9 |
10 | ## License
11 |
12 | Pouch is licensed under the MIT License. See [LICENSE](https://github.com/wzshiming/openapi/blob/master/LICENSE) for the full license text.
13 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/wzshiming/openapi
2 |
3 | go 1.14
4 |
5 | require gopkg.in/yaml.v2 v2.3.0
6 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
2 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
3 | gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
4 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
5 |
--------------------------------------------------------------------------------
/spec/any.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | )
7 |
8 | // NewAny Create an any
9 | func NewAny(v interface{}) Any {
10 | s, _ := json.Marshal(v)
11 | return Any(s)
12 | }
13 |
14 | // Any is a raw encoded JSON value.
15 | // It implements Marshaler and Unmarshaler and can
16 | // be used to delay JSON decoding or precompute a JSON encoding.
17 | type Any []byte
18 |
19 | // MarshalJSON returns m as the JSON encoding of m.
20 | func (m Any) MarshalJSON() ([]byte, error) {
21 | if m == nil {
22 | return []byte("null"), nil
23 | }
24 | return m, nil
25 | }
26 |
27 | // UnmarshalJSON sets *m to a copy of data.
28 | func (m *Any) UnmarshalJSON(data []byte) error {
29 | if m == nil {
30 | return errors.New("Any: UnmarshalJSON on nil pointer")
31 | }
32 | *m = append((*m)[0:0], data...)
33 | return nil
34 | }
35 |
--------------------------------------------------------------------------------
/spec/any_or_expressions.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | )
7 |
8 | // AnyOrExpressions It's the Union type of any and expressions
9 | type AnyOrExpressions struct {
10 | Expressions Expressions
11 | Any Any
12 | }
13 |
14 | // MarshalJSON returns m as the JSON encoding of m.
15 | func (m AnyOrExpressions) MarshalJSON() ([]byte, error) {
16 | if m.Expressions != "" {
17 | return json.Marshal(m.Expressions)
18 | }
19 | return json.Marshal(m.Any)
20 | }
21 |
22 | // UnmarshalJSON sets *m to a copy of data.
23 | func (m *AnyOrExpressions) UnmarshalJSON(data []byte) error {
24 | if m == nil {
25 | return errors.New("spec.AnyOrExpressions: UnmarshalJSON on nil pointer")
26 | }
27 | if len(data) == 0 {
28 | return nil
29 | }
30 | if data[0] == '"' {
31 | return json.Unmarshal(data, &m.Expressions)
32 | }
33 | return json.Unmarshal(data, &m.Any)
34 | }
35 |
--------------------------------------------------------------------------------
/spec/callback.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // callback
4 | type callback map[Expressions]*PathItem
5 |
--------------------------------------------------------------------------------
/spec/callback_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Callback It's the Union type of callback and Refable
11 | type Callback struct {
12 | Refable
13 | callback
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of callback or Refable.
17 | func (m Callback) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.callback)
22 | }
23 |
24 | // UnmarshalJSON sets callback or Refable to data.
25 | func (m *Callback) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Callback: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.callback)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/components.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Components Holds a set of reusable objects for different aspects of the OAS.
4 | // 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.
5 | type Components struct {
6 |
7 | // An object to hold reusable Schema Objects.
8 | Schemas map[string]*Schema `json:"schemas,omitempty"`
9 |
10 | // An object to hold reusable Response Objects.
11 | Responses map[string]*Response `json:"responses,omitempty"`
12 |
13 | // An object to hold reusable Parameter Objects.
14 | Parameters map[string]*Parameter `json:"parameters,omitempty"`
15 |
16 | // An object to hold reusable Example Objects.
17 | Examples map[string]*Example `json:"examples,omitempty"`
18 |
19 | // An object to hold reusable Request Body Objects.
20 | RequestBodies map[string]*RequestBody `json:"requestBodies,omitempty"`
21 |
22 | // An object to hold reusable Header Objects.
23 | Headers map[string]*Header `json:"headers,omitempty"`
24 |
25 | // An object to hold reusable Security Scheme Objects.
26 | SecuritySchemes map[string]*SecurityScheme `json:"securitySchemes,omitempty"`
27 |
28 | // An object to hold reusable Link Objects.
29 | Links map[string]*Link `json:"links,omitempty"`
30 |
31 | // An object to hold reusable Callback Objects.
32 | Callbacks map[string]*Callback `json:"callbacks,omitempty"`
33 | }
34 |
35 | // NewComponents create a new new components
36 | func NewComponents() *Components {
37 | return &Components{
38 | Schemas: map[string]*Schema{},
39 | Responses: map[string]*Response{},
40 | Parameters: map[string]*Parameter{},
41 | Examples: map[string]*Example{},
42 | RequestBodies: map[string]*RequestBody{},
43 | Headers: map[string]*Header{},
44 | SecuritySchemes: map[string]*SecurityScheme{},
45 | Links: map[string]*Link{},
46 | Callbacks: map[string]*Callback{},
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/spec/contact.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Contact information for the exposed API.
4 | type Contact struct {
5 |
6 | // The identifying name of the contact person/organization.
7 | Name string `json:"name"`
8 |
9 | // The URL pointing to the contact information.
10 | // MUST be in the format of a URL.
11 | URL string `json:"url,omitempty"`
12 |
13 | // The email address of the contact person/organization.
14 | // MUST be in the format of an email address.
15 | Email string `json:"email,omitempty"`
16 | }
17 |
--------------------------------------------------------------------------------
/spec/discriminator.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Discriminator When request bodies or response payloads may be one of a number of different schemas, a discriminator object can be used to aid in serialization, deserialization, and validation.
4 | // The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it.
5 | // When using the discriminator, inline schemas will not be considered.
6 | type Discriminator struct {
7 |
8 | // REQUIRED.
9 | // The name of the property in the payload that will hold the discriminator value.
10 | PropertyName string `json:"propertyName"`
11 |
12 | // An object to hold mappings between payload values and schema names or references.
13 | Mapping map[string]string `json:"mapping,omitempty"`
14 | }
15 |
--------------------------------------------------------------------------------
/spec/doc.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | //go:generate go run ./hack/gen_x_or_refable.go -s schema -d Schema -f schema_or_refable.go
4 | //go:generate go run ./hack/gen_x_or_refable.go -s response -d Response -f response_or_refable.go
5 | //go:generate go run ./hack/gen_x_or_refable.go -s parameter -d Parameter -f parameter_or_refable.go
6 | //go:generate go run ./hack/gen_x_or_refable.go -s header -d Header -f header_or_refable.go
7 | //go:generate go run ./hack/gen_x_or_refable.go -s example -d Example -f example_or_refable.go
8 | //go:generate go run ./hack/gen_x_or_refable.go -s requestBody -d RequestBody -f request_body_or_refable.go
9 | //go:generate go run ./hack/gen_x_or_refable.go -s securityScheme -d SecurityScheme -f security_scheme_or_refable.go
10 | //go:generate go run ./hack/gen_x_or_refable.go -s link -d Link -f link_or_refable.go
11 | //go:generate go run ./hack/gen_x_or_refable.go -s callback -d Callback -f callback_or_refable.go
12 |
--------------------------------------------------------------------------------
/spec/encoding.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Encoding A single encoding definition applied to a single schema property.
4 | type Encoding struct {
5 |
6 | // The Content-Type for encoding a specific property.
7 | // Default value depends on the property type: for string with format being binary – application/octet-stream;
8 | // for other primitive types – text/plain; for object - application/json; for array – the default is defined based on the inner type.
9 | // 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.
10 | ContentType string `json:"contentType"`
11 |
12 | // A map allowing additional information to be provided as headers, for example Content-Disposition.
13 | // Content-Type is described separately and SHALL be ignored in this section.
14 | // This property SHALL be ignored if the request body media type is not a multipart.
15 | Headers map[string]*Header `json:"headers,omitempty"`
16 |
17 | // Describes how a specific property value will be serialized depending on its type.
18 | // See Parameter Object for details on the style property.
19 | // The behavior follows the same values as query parameters, including default values.
20 | // This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
21 | Style string `json:"style,omitempty"`
22 |
23 | // When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map.
24 | // For other types of properties this property has no effect.
25 | // When style is form, the default value is true.
26 | // For all other styles, the default value is false.
27 | // This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
28 | Explode bool `json:"explode,omitempty"`
29 |
30 | // Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding.
31 | // The default value is false.
32 | // This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
33 | AllowReserved bool `json:"allowReserved,omitempty"`
34 | }
35 |
--------------------------------------------------------------------------------
/spec/example.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // example
4 | type example struct {
5 |
6 | // Short description for the example.
7 | Summary string `json:"summary,omitempty"`
8 |
9 | // Long description for the example.
10 | // CommonMark syntax MAY be used for rich text representation.
11 | Description string `json:"description,omitempty"`
12 |
13 | // Embedded literal example.
14 | // The value field and externalValue field are mutually exclusive.
15 | // 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.
16 | Value Any `json:"value"`
17 |
18 | // A URL that points to the literal example.
19 | // This provides the capability to reference examples that cannot easily be included in JSON or YAML documents.
20 | // The value field and externalValue field are mutually exclusive.
21 | ExternalValue string `json:"externalValue,omitempty"`
22 | }
23 |
--------------------------------------------------------------------------------
/spec/example_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Example It's the Union type of example and Refable
11 | type Example struct {
12 | Refable
13 | example
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of example or Refable.
17 | func (m Example) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.example)
22 | }
23 |
24 | // UnmarshalJSON sets example or Refable to data.
25 | func (m *Example) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Example: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.example)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/expressions.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | //Expressions Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call.
4 | // This mechanism is used by Link Objects and Callback Objects.
5 | //The runtime expression is defined by the following ABNF syntax
6 | // expression = ( "$url" | "$method" | "$statusCode" | "$request." source | "$response." source )
7 | // source = ( header-reference | query-reference | path-reference | body-reference )
8 | // header-reference = "header." token
9 | // query-reference = "query." name
10 | // path-reference = "path." name
11 | // body-reference = "body" ["#" fragment]
12 | // fragment = a JSON Pointer [RFC 6901](https://tools.ietf.org/html/rfc6901)
13 | // name = *( char )
14 | // char = as per RFC [7159](https://tools.ietf.org/html/rfc7159#section-7)
15 | // token = as per RFC [7230](https://tools.ietf.org/html/rfc7230#section-3.2.6)
16 | //The name identifier is case-sensitive, whereas token is not.
17 | //The table below provides examples of runtime expressions and examples of their use in a value:
18 | type Expressions string
19 |
--------------------------------------------------------------------------------
/spec/external_docs.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // ExternalDocumentation Allows referencing an external resource for extended documentation.
4 | type ExternalDocumentation struct {
5 |
6 | // A short description of the target documentation.
7 | // CommonMark syntax MAY be used for rich text representation.
8 | Description string `json:"description"`
9 |
10 | // REQUIRED.
11 | // The URL for the target documentation.
12 | // Value MUST be in the format of a URL.
13 | URL string `json:"url,omitempty"`
14 | }
15 |
--------------------------------------------------------------------------------
/spec/hack/gen_x_or_array.go:
--------------------------------------------------------------------------------
1 | // +build ignore
2 | package main
3 |
4 | import (
5 | "bytes"
6 | "flag"
7 | "fmt"
8 | "go/format"
9 | "io/ioutil"
10 | "text/template"
11 | )
12 |
13 | var s = flag.String("s", "", "src type name")
14 | var d = flag.String("d", "", "dist type name")
15 | var f = flag.String("f", "", "output file")
16 | var p = flag.String("p", "spec", "package name")
17 |
18 | func main() {
19 | flag.Parse()
20 | if *s == "" || *d == "" {
21 | flag.PrintDefaults()
22 | return
23 | }
24 | t, _ := template.New("").Parse(temp)
25 | buf := bytes.NewBuffer(nil)
26 | t.Execute(buf, map[string]string{
27 | "Src": *s,
28 | "Dist": *d,
29 | "Pkg": *p,
30 | })
31 |
32 | file := buf.Bytes()
33 | file, _ = format.Source(file)
34 | if *f == "" {
35 | fmt.Print(string(file))
36 | return
37 | }
38 | ioutil.WriteFile(*f, file, 0666)
39 | return
40 | }
41 |
42 | const temp = `
43 | // Code generated; DO NOT EDIT.
44 |
45 | package {{ .Pkg }}
46 |
47 | import (
48 | "errors"
49 | "encoding/json"
50 | )
51 |
52 | // {{ .Dist }} It's the Union type of {{ .Src }} and Array
53 | type {{ .Dist }} []{{ .Src }}
54 |
55 | // MarshalJSON returns m as the JSON encoding of m.
56 | func (m {{ .Dist }}) MarshalJSON() ([]byte, error) {
57 | return json.Marshal([]{{ .Src }}(m))
58 | }
59 |
60 | // UnmarshalJSON sets *m to a copy of data.
61 | func (m *{{ .Dist }}) UnmarshalJSON(data []byte) error {
62 | if m == nil {
63 | return errors.New("spec.{{ .Dist }}: UnmarshalJSON on nil pointer")
64 | }
65 | if len(data) == 0 {
66 | return nil
67 | }
68 | if data[0] != '[' {
69 | var s {{ .Src }}
70 | err := json.Unmarshal(data, &s)
71 | if err != nil {
72 | return err
73 | }
74 | *m = []{{ .Src }}{s}
75 | return nil
76 | }
77 |
78 | return json.Unmarshal(data, []{{ .Src }}(*m))
79 | }
80 |
81 | `
82 |
--------------------------------------------------------------------------------
/spec/hack/gen_x_or_refable.go:
--------------------------------------------------------------------------------
1 | // +build ignore
2 | package main
3 |
4 | import (
5 | "bytes"
6 | "flag"
7 | "fmt"
8 | "go/format"
9 | "io/ioutil"
10 | "text/template"
11 | )
12 |
13 | var s = flag.String("s", "", "src type name")
14 | var d = flag.String("d", "", "dist type name")
15 | var f = flag.String("f", "", "output file")
16 | var p = flag.String("p", "spec", "package name")
17 |
18 | func main() {
19 | flag.Parse()
20 | if *s == "" || *d == "" {
21 | flag.PrintDefaults()
22 | return
23 | }
24 | t, _ := template.New("").Parse(temp)
25 | buf := bytes.NewBuffer(nil)
26 | t.Execute(buf, map[string]string{
27 | "Src": *s,
28 | "Dist": *d,
29 | "Pkg": *p,
30 | })
31 |
32 | file := buf.Bytes()
33 | file, _ = format.Source(file)
34 | if *f == "" {
35 | fmt.Print(string(file))
36 | return
37 | }
38 | ioutil.WriteFile(*f, file, 0666)
39 | return
40 | }
41 |
42 | const temp = `
43 | // Code generated; DO NOT EDIT.
44 |
45 | package {{ .Pkg }}
46 |
47 | import (
48 | "errors"
49 | "encoding/json"
50 | )
51 |
52 | // {{ .Dist }} It's the Union type of {{ .Src }} and Refable
53 | type {{ .Dist }} struct {
54 | Refable
55 | {{ .Src }}
56 | }
57 |
58 | // MarshalJSON returns m as the JSON encoding of {{ .Src }} or Refable.
59 | func (m {{ .Dist }}) MarshalJSON() ([]byte, error) {
60 | if m.Ref != "" {
61 | return json.Marshal(m.Refable)
62 | }
63 | return json.Marshal(m.{{ .Src }})
64 | }
65 |
66 | // UnmarshalJSON sets {{ .Src }} or Refable to data.
67 | func (m *{{ .Dist }}) UnmarshalJSON(data []byte) error {
68 | if m == nil {
69 | return errors.New("spec.{{ .Dist }}: UnmarshalJSON on nil pointer")
70 | }
71 | if len(data) == 0 {
72 | return nil
73 | }
74 | err := json.Unmarshal(data, &m.Refable)
75 | if err != nil {
76 | return err
77 | }
78 | if m.Ref != "" {
79 | return nil
80 | }
81 | return json.Unmarshal(data, &m.{{ .Src }})
82 | }
83 |
84 | `
85 |
--------------------------------------------------------------------------------
/spec/header.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Header The Header Object follows the structure of the Parameter Object with the following changes:
4 | // 1. name MUST NOT be specified, it is given in the corresponding headers map.
5 | // 2. in MUST NOT be specified, it is implicitly in header.
6 | // 3. All traits that are affected by the location MUST be applicable to a location of header (for example, style).
7 | type header struct {
8 |
9 | // A brief description of the parameter.
10 | // This could contain examples of use.
11 | // CommonMark syntax MAY be used for rich text representation.
12 | Description string `json:"description,omitempty"`
13 |
14 | // Determines whether this parameter is mandatory.
15 | // If the parameter location is "path", this property is REQUIRED and its value MUST be true.
16 | // Otherwise, the property MAY be included and its default value is false.
17 | Required bool `json:"required,omitempty"`
18 |
19 | // Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
20 | Deprecated bool `json:"deprecated,omitempty"`
21 |
22 | // Sets the ability to pass empty-valued parameters.
23 | // This is valid only for query parameters and allows sending a parameter with an empty value.
24 | // Default value is false.
25 | // If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored.
26 | AllowEmptyValue bool `json:"allowEmptyValue,omitempty"`
27 |
28 | // The rules for serialization of the parameter are specified in one of two ways.
29 | // For simpler scenarios, a schema and style can describe the structure and syntax of the parameter.
30 |
31 | // Describes how the parameter value will be serialized depending on the type of the parameter value.
32 | // Default values (based on value of in): for query - form; for path - simple; for header - simple; for cookie - form.
33 | Style string `json:"style,omitempty"`
34 |
35 | // When this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map.
36 | // For other types of parameters this property has no effect.
37 | // When style is form, the default value is true.
38 | // For all other styles, the default value is false.
39 | Explode bool `json:"explode"`
40 |
41 | // Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding.
42 | // This property only applies to parameters with an in value of query.
43 | // The default value is false.
44 | AllowReserved bool `json:"allowReserved,omitempty"`
45 |
46 | // The schema defining the type used for the parameter.
47 | Schema *Schema `json:"schema,omitempty"`
48 |
49 | // Example of the media type.
50 | // The example SHOULD match the specified schema and encoding properties if present.
51 | // The example field is mutually exclusive of the examples field.
52 | // Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema.
53 | // 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.
54 | Example Any `json:"example,omitempty"`
55 |
56 | // Examples of the media type.
57 | // Each example SHOULD contain a value in the correct format as specified in the parameter encoding.
58 | // The examples field is mutually exclusive of the example field.
59 | // Furthermore, if referencing a schema which contains an example, the examples value SHALL override the example provided by the schema.
60 | Examples map[string]*Example `json:"examples,omitempty"`
61 |
62 | // For more complex scenarios, the content property can define the media type and schema of the parameter.
63 | // A parameter MUST contain either a schema property, or a content property, but not both.
64 | // When example or examples are provided in conjunction with the schema object, the example MUST follow the prescribed serialization strategy for the parameter.
65 |
66 | // A map containing the representations for the parameter.
67 | // The key is the media type and the value describes it.
68 | // The map MUST only contain one entry.
69 | Content map[string]*MediaType `json:"content,omitempty"`
70 | }
71 |
--------------------------------------------------------------------------------
/spec/header_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Header It's the Union type of header and Refable
11 | type Header struct {
12 | Refable
13 | header
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of header or Refable.
17 | func (m Header) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.header)
22 | }
23 |
24 | // UnmarshalJSON sets header or Refable to data.
25 | func (m *Header) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Header: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.header)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/header_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // WithDescription sets the description on this response, allows for chaining
4 | func (h *Header) WithDescription(description string) *Header {
5 | h.Description = description
6 | return h
7 | }
8 |
9 | // AllowsEmptyValues flags this parameter as being ok with empty values
10 | func (h *Header) AllowsEmptyValues() *Header {
11 | h.AllowEmptyValue = true
12 | return h
13 | }
14 |
15 | // NoEmptyValues flags this parameter as not liking empty values
16 | func (h *Header) NoEmptyValues() *Header {
17 | h.AllowEmptyValue = false
18 | return h
19 | }
20 |
21 | // AsOptional flags this parameter as optional
22 | func (h *Header) AsOptional() *Header {
23 | h.Required = false
24 | return h
25 | }
26 |
--------------------------------------------------------------------------------
/spec/info.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Info The object provides metadata about the API.
4 | // The metadata MAY be used by the clients if needed,
5 | // and MAY be presented in editing or documentation generation tools for convenience.
6 | type Info struct {
7 |
8 | // REQUIRED.
9 | // The title of the application.
10 | Title string `json:"title"`
11 |
12 | // A short description of the application.
13 | // CommonMark syntax MAY be used for rich text representation.
14 | Description string `json:"description,omitempty"`
15 |
16 | // A URL to the Terms of Service for the API.
17 | // MUST be in the format of a URL.
18 | TermsOfService string `json:"termsOfService,omitempty"`
19 |
20 | // The contact information for the exposed API.
21 | Contact *Contact `json:"contact,omitempty"`
22 |
23 | // The license information for the exposed API.
24 | License *License `json:"license,omitempty"`
25 |
26 | // REQUIRED.
27 | // The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
28 | Version string `json:"version"`
29 | }
30 |
--------------------------------------------------------------------------------
/spec/license.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // License information for the exposed API.
4 | type License struct {
5 |
6 | // REQUIRED.
7 | // The license name used for the API.
8 | Name string `json:"name"`
9 |
10 | // A URL to the license used for the API.
11 | // MUST be in the format of a URL.
12 | URL string `json:"url,omitempty"`
13 | }
14 |
--------------------------------------------------------------------------------
/spec/link.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // link The Link object represents a possible design-time link for a response.
4 | // 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.
5 | // Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.
6 | // 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.
7 | type link struct {
8 |
9 | // A relative or absolute reference to an OAS operation.
10 | // This field is mutually exclusive of the operationId field, and MUST point to an Operation Object.
11 | // Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition.
12 | OperationRef string `json:"operationRef,omitempty"`
13 |
14 | // The name of an existing, resolvable OAS operation, as defined with a unique operationId.
15 | // This field is mutually exclusive of the operationRef field.
16 | OperationID string `json:"operationId,omitempty"`
17 |
18 | // A map representing parameters to pass to an operation as specified with operationId or identified via operationRef.
19 | // 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.
20 | // 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).
21 | Parameters map[string]*AnyOrExpressions `json:"parameters,omitempty"`
22 |
23 | // A literal value or to use as a request body when calling the target operation.
24 | RequestBody *AnyOrExpressions `json:"requestBody,omitempty"`
25 |
26 | // A description of the link.
27 | // CommonMark syntax MAY be used for rich text representation.
28 | Description string `json:"description,omitempty"`
29 |
30 | // A server object to be used by the target operation.
31 | Server *Server `json:"server,omitempty"`
32 | }
33 |
--------------------------------------------------------------------------------
/spec/link_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Link It's the Union type of link and Refable
11 | type Link struct {
12 | Refable
13 | link
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of link or Refable.
17 | func (m Link) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.link)
22 | }
23 |
24 | // UnmarshalJSON sets link or Refable to data.
25 | func (m *Link) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Link: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.link)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/media_type.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // MediaType Each Media Type Object provides schema and examples for the media type identified by its key.
4 | type MediaType struct {
5 | // The schema defining the type used for the request body.
6 | Schema *Schema `json:"schema,omitempty"`
7 |
8 | // Any Example of the media type.
9 | // The example object SHOULD be in the correct format as specified by the media type.
10 | // The example field is mutually exclusive of the examples field.
11 | // Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema.
12 | Example Any `json:"example,omitempty"`
13 |
14 | // Examples of the media type. Each example object SHOULD match the media type and specified schema if present.
15 | // 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.
16 | Examples map[string]*Example `json:"examples,omitempty"`
17 |
18 | // A map between a property name and its encoding information.
19 | // The key, being the property name, MUST exist in the schema as a property.
20 | // The encoding object SHALL only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded.
21 | Encoding map[string]*Encoding `json:"encoding,omitempty"`
22 | }
23 |
--------------------------------------------------------------------------------
/spec/oauth_flow.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // OAuthFlow Configuration details for a supported OAuth Flow
4 | type OAuthFlow struct {
5 |
6 | // oauth2 ("implicit", "authorizationCode")
7 | // REQUIRED.
8 | // The authorization URL to be used for this flow.
9 | // This MUST be in the form of a URL.
10 | AuthorizationURL string `json:"authorizationUrl,omitempty"`
11 |
12 | // oauth2 ("password", "clientCredentials", "authorizationCode")
13 | // REQUIRED.
14 | // The token URL to be used for this flow.
15 | // This MUST be in the form of a URL.
16 | TokenURL string `json:"tokenUrl,omitempty"`
17 |
18 | // oauth2 The URL to be used for obtaining refresh tokens.
19 | // This MUST be in the form of a URL.
20 | RefreshURL string `json:"refreshUrl,omitempty"`
21 |
22 | // oauth2
23 | // REQUIRED.
24 | // The available scopes for the OAuth2 security scheme.
25 | // A map between the scope name and a short description for it.
26 | Acopes map[string]string `json:"acopes,omitempty"`
27 | }
28 |
--------------------------------------------------------------------------------
/spec/oauth_flows.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // OAuthFlows Allows configuration of the supported OAuth Flows.
4 | type OAuthFlows struct {
5 |
6 | // Configuration for the OAuth Implicit flow
7 | Implicit *OAuthFlow `json:"implicit,omitempty"`
8 |
9 | // Configuration for the OAuth Resource Owner Password flow
10 | Password *OAuthFlow `json:"password,omitempty"`
11 |
12 | // Configuration for the OAuth Client Credentials flow.
13 | // Previously called application in OpenAPI 2.0.
14 | ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
15 |
16 | // Configuration for the OAuth Authorization Code flow.
17 | // Previously called accessCode in OpenAPI 2.0.
18 | AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
19 | }
20 |
--------------------------------------------------------------------------------
/spec/openapi.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // OpenAPI This is the root document object of the OpenAPI document.
4 | type OpenAPI struct {
5 |
6 | // REQUIRED.
7 | // This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses.
8 | // The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document.
9 | // This is not related to the API info.version string.
10 | OpenAPI string `json:"openapi,omitempty"`
11 |
12 | // REQUIRED.
13 | // Provides metadata about the API.
14 | // The metadata MAY be used by tooling as required.
15 | Info *Info `json:"info,omitempty"`
16 |
17 | // An array of Server Objects, which provide connectivity information to a target server.
18 | // 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 /.
19 | Servers []*Server `json:"servers,omitempty"`
20 |
21 | // REQUIRED.
22 | // The available paths and operations for the API.
23 | Paths Paths `json:"paths,omitempty"`
24 |
25 | // An element to hold various schemas for the specification.
26 | Components *Components `json:"components,omitempty"`
27 |
28 | // A declaration of which security mechanisms can be used across the API.
29 | // The list of values includes alternative security requirement objects that can be used.
30 | // Only one of the security requirement objects need to be satisfied to authorize a request.
31 | // Individual operations can override this definition.
32 | Security []map[string]SecurityRequirement `json:"security,omitempty"`
33 |
34 | // A list of tags used by the specification with additional metadata.
35 | // The order of the tags can be used to reflect on their order by the parsing tools.
36 | // Not all tags that are used by the Operation Object must be declared.
37 | // The tags that are not declared MAY be organized randomly or based on the tools' logic.
38 | // Each tag name in the list MUST be unique.
39 | Tags []*Tag `json:"tags,omitempty"`
40 |
41 | // Additional extern
42 | ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
43 | }
44 |
--------------------------------------------------------------------------------
/spec/operation.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Operation Describes a single API operation on a path.
4 | type Operation struct {
5 |
6 | // A list of tags for API documentation control.
7 | // Tags can be used for logical grouping of operations by resources or any other qualifier.
8 | Tags []string `json:"tags,omitempty"`
9 |
10 | // A short summary of what the operation does.
11 | Summary string `json:"summary,omitempty"`
12 |
13 | // A verbose explanation of the operation behavior.
14 | // CommonMark syntax MAY be used for rich text representation.
15 | Description string `json:"description,omitempty"`
16 |
17 | // Additional external documentation for this operation.
18 | ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
19 |
20 | // Unique string used to identify the operation.
21 | // The id MUST be unique among all operations described in the API.
22 | // Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions.
23 | OperationID string `json:"operationId,omitempty"`
24 |
25 | // A list of parameters that are applicable for this operation.
26 | // If a parameter is already defined at the Path Item, the new definition will override it but can never remove it.
27 | // The list MUST NOT include duplicated parameters.
28 | // A unique parameter is defined by a combination of a name and location.
29 | // The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
30 | Parameters []*Parameter `json:"parameters,omitempty"`
31 |
32 | // The request body applicable for this operation.
33 | // The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies.
34 | // In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
35 | RequestBody *RequestBody `json:"requestBody,omitempty"`
36 |
37 | // REQUIRED.
38 | // The list of possible responses as they are returned from executing this operation.
39 | Responses map[string]*Response `json:"responses,omitempty"`
40 |
41 | // A map of possible out-of band callbacks related to the parent operation.
42 | // The key is a unique identifier for the Callback Object.
43 | // 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.
44 | // The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
45 | Callbacks map[string]*Callback `json:"callbacks,omitempty"`
46 |
47 | // Declares this operation to be deprecated.
48 | // Consumers SHOULD refrain from usage of the declared operation.
49 | // Default value is false.
50 | Deprecated bool `json:"deprecated,omitempty"`
51 |
52 | // A declaration of which security mechanisms can be used for this operation.
53 | // The list of values includes alternative security requirement objects that can be used.
54 | // Only one of the security requirement objects need to be satisfied to authorize a request.
55 | // This definition overrides any declared top-level security.
56 | // To remove a top-level security declaration, an empty array can be used.
57 | Security []map[string]SecurityRequirement `json:"security,omitempty"`
58 |
59 | // An alternative server array to service this operation.
60 | // If an alternative server object is specified at the Path Item Object or Root level, it will be overridden by this value.
61 | Servers []*Server `json:"servers,omitempty"`
62 | }
63 |
--------------------------------------------------------------------------------
/spec/parameter.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // parameter Describes a single operation parameter.
4 | // A unique parameter is defined by a combination of a name and location.
5 | // Parameter Locations
6 | // There are four possible parameter locations specified by the in field:
7 | // path - Used together with Path Templating, where the parameter value is actually part of the operation's URL.
8 | // This does not include the host or base path of the API.
9 | // For example, in /items/{itemId}, the path parameter is itemId.
10 | // query - Parameters that are appended to the URL.
11 | // For example, in /items?id=###, the query parameter is id.
12 | // header - Custom headers that are expected as part of the request.
13 | // Note that RFC7230 states header names are case insensitive.
14 | // cookie - Used to pass a specific cookie value to the API.
15 | type parameter struct {
16 |
17 | // REQUIRED.
18 | // The name of the parameter.
19 | // Parameter names are case sensitive.
20 | // If in is "path", the name field MUST correspond to the associated path segment from the path field in the Paths Object.
21 | // See Path Templating for further information.
22 | // If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored.
23 | // For all other cases, the name corresponds to the parameter name used by the in property.
24 | Name string `json:"name"`
25 |
26 | // REQUIRED.
27 | // The location of the parameter.
28 | // Possible values are "query", "header", "path" or "cookie".
29 | In string `json:"in"`
30 |
31 | header
32 | }
33 |
--------------------------------------------------------------------------------
/spec/parameter_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Parameter It's the Union type of parameter and Refable
11 | type Parameter struct {
12 | Refable
13 | parameter
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of parameter or Refable.
17 | func (m Parameter) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.parameter)
22 | }
23 |
24 | // UnmarshalJSON sets parameter or Refable to data.
25 | func (m *Parameter) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Parameter: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.parameter)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/parameter_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Parameter Locations
4 | // There are four possible parameter locations specified by the in field:
5 | const (
6 | InPath = "path" // Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId.
7 | InQuery = "query" // Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
8 | InHeader = "header" // Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive.
9 | InCookie = "cookie" // Used to pass a specific cookie value to the API.
10 | )
11 |
12 | // QueryParam creates a query parameter
13 | func QueryParam(name string, schema *Schema) *Parameter {
14 | p := &Parameter{}
15 | p.In = InQuery
16 | p.Name = name
17 | p.Schema = schema
18 | return p
19 | }
20 |
21 | // HeaderParam creates a header parameter, this is always required by default
22 | func HeaderParam(name string, schema *Schema) *Parameter {
23 | p := &Parameter{}
24 | p.In = InHeader
25 | p.Name = name
26 | p.Schema = schema
27 | return p
28 | }
29 |
30 | // PathParam creates a path parameter, this is always required
31 | func PathParam(name string, schema *Schema) *Parameter {
32 | p := &Parameter{}
33 | p.In = InPath
34 | p.Name = name
35 | p.Schema = schema
36 | p.Required = true
37 | return p
38 | }
39 |
40 | // CookieParam creates a path parameter, this is always required
41 | func CookieParam(name string, schema *Schema) *Parameter {
42 | p := &Parameter{}
43 | p.In = InCookie
44 | p.Name = name
45 | p.Schema = schema
46 | return p
47 | }
48 |
49 | // WithDescription sets the description on this response, allows for chaining
50 | func (p *Parameter) WithDescription(description string) *Parameter {
51 | p.Description = description
52 | return p
53 | }
54 |
55 | // WithName a fluent builder method to override the name of the parameter
56 | func (p *Parameter) WithName(name string) *Parameter {
57 | p.Name = name
58 | return p
59 | }
60 |
61 | // WithSchema a fluent builder method to override the schema of the parameter
62 | func (p *Parameter) WithSchema(schema *Schema) *Parameter {
63 | p.Schema = schema
64 | return p
65 | }
66 |
67 | // WithLocation a fluent builder method to override the location of the parameter
68 | func (p *Parameter) WithLocation(in string) *Parameter {
69 | p.In = in
70 | return p
71 | }
72 |
73 | // AllowsEmptyValues flags this parameter as being ok with empty values
74 | func (p *Parameter) AllowsEmptyValues() *Parameter {
75 | p.AllowEmptyValue = true
76 | return p
77 | }
78 |
79 | // NoEmptyValues flags this parameter as not liking empty values
80 | func (p *Parameter) NoEmptyValues() *Parameter {
81 | p.AllowEmptyValue = false
82 | return p
83 | }
84 |
85 | // AsOptional flags this parameter as optional
86 | func (p *Parameter) AsOptional() *Parameter {
87 | p.Required = false
88 | return p
89 | }
90 |
--------------------------------------------------------------------------------
/spec/paths.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Paths Holds the relative paths to the individual endpoints and their operations.
4 | // The path is appended to the URL from the Server Object in order to construct the full URL.
5 | // The Paths MAY be empty, due to ACL constraints.
6 | type Paths map[string]*PathItem
7 |
8 | // PathItem Describes the operations available on a single path.
9 | // A Path Item MAY be empty, due to ACL constraints.
10 | // The path itself is still exposed to the documentation viewer but they will
11 | // not know which operations and parameters are available.
12 | type PathItem struct {
13 |
14 | // An optional, string summary, intended to apply to all operations in this path.
15 | Summary string `json:"summary,omitempty"`
16 |
17 | // An optional, string description, intended to apply to all operations in this path.
18 | // CommonMark syntax MAY be used for rich text representation.
19 | Description string `json:"description,omitempty"`
20 |
21 | // A definition of a GET operation on this path.
22 | Get *Operation `json:"get,omitempty"`
23 |
24 | // A definition of a PUT operation on this path.
25 | Put *Operation `json:"put,omitempty"`
26 |
27 | // A definition of a POST operation on this path.
28 | Post *Operation `json:"post,omitempty"`
29 |
30 | // A definition of a DELETE operation on this path.
31 | Delete *Operation `json:"delete,omitempty"`
32 |
33 | // A definition of a OPTIONS operation on this path.
34 | Options *Operation `json:"options,omitempty"`
35 |
36 | // A definition of a HEAD operation on this path.
37 | Head *Operation `json:"head,omitempty"`
38 |
39 | // A definition of a PATCH operation on this path.
40 | Patch *Operation `json:"patch,omitempty"`
41 |
42 | // A definition of a TRACE operation on this path.
43 | Trace *Operation `json:"trace,omitempty"`
44 |
45 | // An alternative server array to service all operations in this path.
46 | Servers []*Server `json:"servers,omitempty"`
47 |
48 | // A list of parameters that are applicable for all the operations described under this path.
49 | // These parameters can be overridden at the operation level, but cannot be removed there.
50 | // The list MUST NOT include duplicated parameters.
51 | // A unique parameter is defined by a combination of a name and location.
52 | // The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters.
53 | Parameters []*Parameter `json:"parameters,omitempty"`
54 | }
55 |
--------------------------------------------------------------------------------
/spec/refable.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | "strings"
7 | )
8 |
9 | // Refable A simple object to allow referencing other components in the specification, internally and externally.
10 | // The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules.
11 | // For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.
12 | type Refable struct {
13 | // REQUIRED.
14 | // The reference string.
15 | Ref string
16 | Components string
17 | }
18 |
19 | // MarshalJSON returns m as the JSON encoding of m.
20 | func (m Refable) MarshalJSON() ([]byte, error) {
21 | if m.Ref == "" {
22 | return []byte("{}"), nil
23 | }
24 | return json.Marshal(ref{m.Components + m.Ref})
25 | }
26 |
27 | // UnmarshalJSON sets *m to a copy of data.
28 | func (m *Refable) UnmarshalJSON(data []byte) error {
29 | if m == nil {
30 | return errors.New("spec.Refable: UnmarshalJSON on nil pointer")
31 | }
32 | ref := ref{}
33 | err := json.Unmarshal(data, &ref)
34 | if err != nil {
35 | return err
36 | }
37 | i := strings.LastIndex(ref.Ref, "/")
38 | m.Components = ref.Ref[:i+1]
39 | m.Ref = ref.Ref[i+1:]
40 | return nil
41 | }
42 |
43 | type ref struct {
44 | Ref string `json:"$ref,omitempty"`
45 | }
46 |
--------------------------------------------------------------------------------
/spec/refable_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // RefSchemas creates a ref schemas
4 | func RefSchemas(ref string) *Schema {
5 | s := &Schema{}
6 | s.Components = "#/components/schemas/"
7 | s.Ref = ref
8 | return s
9 | }
10 |
11 | // RefResponse creates a ref responses
12 | func RefResponse(ref string) *Response {
13 | r := &Response{}
14 | r.Components = "#/components/responses/"
15 | r.Ref = ref
16 | return r
17 | }
18 |
19 | // RefParameter creates a ref rarameter
20 | func RefParameter(ref string) *Parameter {
21 | p := &Parameter{}
22 | p.Components = "#/components/parameters/"
23 | p.Ref = ref
24 | return p
25 | }
26 |
27 | // RefExample creates a ref example
28 | func RefExample(ref string) *Example {
29 | e := &Example{}
30 | e.Components = "#/components/examples/"
31 | e.Ref = ref
32 | return e
33 | }
34 |
35 | // RefRequestBody creates a ref request body
36 | func RefRequestBody(ref string) *RequestBody {
37 | r := &RequestBody{}
38 | r.Components = "#/components/requestBodies/"
39 | r.Ref = ref
40 | return r
41 | }
42 |
43 | // RefHeader creates a ref header
44 | func RefHeader(ref string) *Header {
45 | h := &Header{}
46 | h.Components = "#/components/headers/"
47 | h.Ref = ref
48 | return h
49 | }
50 |
51 | // RefSecurityScheme creates a ref security schemes
52 | func RefSecurityScheme(ref string) *SecurityScheme {
53 | s := &SecurityScheme{}
54 | s.Components = "#/components/securitySchemes/"
55 | s.Ref = ref
56 | return s
57 | }
58 |
59 | // RefLink creates a ref link
60 | func RefLink(ref string) *Link {
61 | l := &Link{}
62 | l.Components = "#/components/links/"
63 | l.Ref = ref
64 | return l
65 | }
66 |
67 | // RefCallback creates a ref callback
68 | func RefCallback(ref string) *Callback {
69 | c := &Callback{}
70 | c.Components = "#/components/callbacks/"
71 | c.Ref = ref
72 | return c
73 | }
74 |
--------------------------------------------------------------------------------
/spec/request_body.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // requestBody Describes a single request body.
4 | type requestBody struct {
5 |
6 | // A brief description of the request body.
7 | // This could contain examples of use.
8 | // CommonMark syntax MAY be used for rich text representation.
9 | Description string `json:"description,omitempty"`
10 |
11 | // REQUIRED.
12 | // The content of the request body.
13 | // The key is a media type or media type range and the value describes it.
14 | // For requests that match multiple keys, only the most specific key is applicable.
15 | // e.g. text/plain overrides text/*
16 | Content map[string]*MediaType `json:"content"`
17 |
18 | // Determines if the request body is required in the request.
19 | // Defaults to false.
20 | Required bool `json:"required,omitempty"`
21 | }
22 |
--------------------------------------------------------------------------------
/spec/request_body_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // RequestBody It's the Union type of requestBody and Refable
11 | type RequestBody struct {
12 | Refable
13 | requestBody
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of requestBody or Refable.
17 | func (m RequestBody) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.requestBody)
22 | }
23 |
24 | // UnmarshalJSON sets requestBody or Refable to data.
25 | func (m *RequestBody) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.RequestBody: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.requestBody)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/request_body_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Media type definitions are spread across several resources. The media type definitions SHOULD be in compliance with RFC6838.
4 | // Some examples of possible media type definitions:
5 | const (
6 | MimeJSON = "application/json"
7 | MimeXML = "application/xml"
8 | MimeTextPlain = "text/plain"
9 | MimeOctetStream = "application/octet-stream"
10 | MimeURLEncoded = "application/x-www-form-urlencoded"
11 | MimeFormData = "multipart/form-data"
12 | )
13 |
14 | // JSONRequestBody creates a request body
15 | func JSONRequestBody(schema *Schema) *RequestBody {
16 | return NewRequestBody(MimeJSON, schema)
17 | }
18 |
19 | // XMLRequestBody creates a request body
20 | func XMLRequestBody(schema *Schema) *RequestBody {
21 | return NewRequestBody(MimeXML, schema)
22 | }
23 |
24 | // TextPlainRequestBody creates a request body
25 | func TextPlainRequestBody(schema *Schema) *RequestBody {
26 | return NewRequestBody(MimeTextPlain, schema)
27 | }
28 |
29 | // OctetStreamRequestBody creates a request body
30 | func OctetStreamRequestBody(schema *Schema) *RequestBody {
31 | return NewRequestBody(MimeOctetStream, schema)
32 | }
33 |
34 | // URLEncodedRequestBody creates a request body
35 | func URLEncodedRequestBody(schema *Schema) *RequestBody {
36 | return NewRequestBody(MimeURLEncoded, schema)
37 | }
38 |
39 | // FormDataRequestBody creates a request body
40 | func FormDataRequestBody(schema *Schema) *RequestBody {
41 | return NewRequestBody(MimeFormData, schema)
42 | }
43 |
44 | // NewRequestBody creates a request body
45 | func NewRequestBody(typ string, schema *Schema) *RequestBody {
46 | rb := &RequestBody{}
47 | rb.Content = map[string]*MediaType{
48 | typ: &MediaType{
49 | Schema: schema,
50 | },
51 | }
52 | return rb
53 | }
54 |
--------------------------------------------------------------------------------
/spec/response.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Response Describes a single response from an API Operation, including design-time, static links to operations based on the response.
4 | type response struct {
5 |
6 | // REQUIRED.
7 | // A short description of the response.
8 | // CommonMark syntax MAY be used for rich text representation.
9 | Description string `json:"description,omitempty"`
10 |
11 | // Maps a header name to its definition.
12 | // RFC7230 states header names are case insensitive.
13 | // If a response header is defined with the name "Content-Type", it SHALL be ignored.
14 | Headers map[string]*Header `json:"headers,omitempty"`
15 |
16 | // A map containing descriptions of potential response payloads.
17 | // The key is a media type or media type range and the value describes it.
18 | // For responses that match multiple keys, only the most specific key is applicable.
19 | // e.g. text/plain overrides text/*
20 | Content map[string]*MediaType `json:"content"`
21 |
22 | // A map of operations links that can be followed from the response.
23 | // The key of the map is a short name for the link, following the naming constraints of the names for Component Objects.
24 | Links map[string]*Link `json:"links,omitempty"`
25 | }
26 |
--------------------------------------------------------------------------------
/spec/response_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Response It's the Union type of response and Refable
11 | type Response struct {
12 | Refable
13 | response
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of response or Refable.
17 | func (m Response) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.response)
22 | }
23 |
24 | // UnmarshalJSON sets response or Refable to data.
25 | func (m *Response) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Response: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.response)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/response_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // JSONResponse creates a request body
4 | func JSONResponse(schema *Schema) *Response {
5 | return NewResponse(MimeJSON, schema)
6 | }
7 |
8 | // XMLResponse creates a request body
9 | func XMLResponse(schema *Schema) *Response {
10 | return NewResponse(MimeXML, schema)
11 | }
12 |
13 | // TextPlainResponse creates a request body
14 | func TextPlainResponse(schema *Schema) *Response {
15 | return NewResponse(MimeTextPlain, schema)
16 | }
17 |
18 | // OctetStreamResponse creates a request body
19 | func OctetStreamResponse(schema *Schema) *Response {
20 | return NewResponse(MimeOctetStream, schema)
21 | }
22 |
23 | // URLEncodedResponse creates a request body
24 | func URLEncodedResponse(schema *Schema) *Response {
25 | return NewResponse(MimeURLEncoded, schema)
26 | }
27 |
28 | // FormDataResponse creates a request body
29 | func FormDataResponse(schema *Schema) *Response {
30 | return NewResponse(MimeFormData, schema)
31 | }
32 |
33 | // NewResponse creates a response
34 | func NewResponse(typ string, schema *Schema) *Response {
35 | rb := &Response{}
36 | rb.Content = map[string]*MediaType{
37 | typ: &MediaType{
38 | Schema: schema,
39 | },
40 | }
41 | return rb
42 | }
43 |
44 | // WithDescription sets the description on this response, allows for chaining
45 | func (r *Response) WithDescription(description string) *Response {
46 | r.Description = description
47 | return r
48 | }
49 |
50 | // AddHeader adds a header to this response
51 | func (r *Response) AddHeader(name string, header *Header) *Response {
52 | if header == nil {
53 | return r.RemoveHeader(name)
54 | }
55 | if r.Headers == nil {
56 | r.Headers = map[string]*Header{}
57 | }
58 | r.Headers[name] = header
59 | return r
60 | }
61 |
62 | // RemoveHeader removes a header from this response
63 | func (r *Response) RemoveHeader(name string) *Response {
64 | delete(r.Headers, name)
65 | return r
66 | }
67 |
68 | // AddContent adds a content to this response
69 | func (r *Response) AddContent(name string, content *MediaType) *Response {
70 | if content == nil {
71 | return r.RemoveHeader(name)
72 | }
73 | if r.Content == nil {
74 | r.Content = map[string]*MediaType{}
75 | }
76 | r.Content[name] = content
77 | return r
78 | }
79 |
80 | // RemoveContent removes a content from this response
81 | func (r *Response) RemoveContent(name string) *Response {
82 | delete(r.Content, name)
83 | return r
84 | }
85 |
86 | // AddLink adds a link to this response
87 | func (r *Response) AddLink(name string, link *Link) *Response {
88 | if link == nil {
89 | return r.RemoveHeader(name)
90 | }
91 | if r.Links == nil {
92 | r.Links = map[string]*Link{}
93 | }
94 | r.Links[name] = link
95 | return r
96 | }
97 |
98 | // RemoveLink removes a link from this response
99 | func (r *Response) RemoveLink(name string) *Response {
100 | delete(r.Links, name)
101 | return r
102 | }
103 |
--------------------------------------------------------------------------------
/spec/schema.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // schema The Schema Object allows the definition of input and output data types.
4 | // These types can be objects, but also primitives and arrays.
5 | // This object is an extended subset of the JSON Schema Specification Wright Draft 00.
6 | // For more information about the properties, see JSON Schema Core and JSON Schema Validation.
7 | // Unless stated otherwise, the property definitions follow the JSON Schema.
8 | type schema struct {
9 |
10 | // Allows sending a null value for the defined schema.
11 | // Default value is false.
12 | Nullable bool `json:"nullable,omitempty"`
13 |
14 | // Adds support for polymorphism.
15 | // The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description.
16 | // See Composition and Inheritance for more details.
17 | Discriminator *Discriminator `json:"discriminator,omitempty"`
18 |
19 | // Relevant only for Schema "properties" definitions.
20 | // Declares the property as "read only".
21 | // This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request.
22 | // If the property is marked as readOnly being true and is in the required list, the required will take effect on the response only.
23 | // A property MUST NOT be marked as both readOnly and writeOnly being true.
24 | // Default value is false.
25 | ReadOnly bool `json:"readOnly,omitempty"`
26 |
27 | // Relevant only for Schema "properties" definitions.
28 | // Declares the property as "write only".
29 | // Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response.
30 | // If the property is marked as writeOnly being true and is in the required list, the required will take effect on the request only.
31 | // A property MUST NOT be marked as both readOnly and writeOnly being true.
32 | // Default value is false.
33 | WriteOnly bool `json:"writeOnly,omitempty"`
34 |
35 | // This MAY be used only on properties schemas.
36 | // It has no effect on root schemas.
37 | // Adds additional metadata to describe the XML representation of this property.
38 | XML *XML `json:"xml,omitempty"`
39 |
40 | // Additional external documentation for this schema.
41 | ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
42 |
43 | // Any A free-form property to include an example of an instance for this schema.
44 | // To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.
45 | Example Any `json:"example,omitempty"`
46 |
47 | // Specifies that a schema is deprecated and SHOULD be transitioned out of usage.
48 | // Default value is false.
49 | Deprecated bool `json:"deprecated,omitempty"`
50 |
51 | // The following properties are taken directly from the JSON Schema definition and follow the same specifications:
52 |
53 | Title string `json:"title,omitempty"`
54 |
55 | // Numbers
56 | MultipleOf *float64 `json:"multipleOf,omitempty"`
57 | Maximum *float64 `json:"maximum,omitempty"`
58 | ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
59 | Minimum *float64 `json:"minimum,omitempty"`
60 | ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
61 |
62 | // Strings
63 | MaxLength *int64 `json:"maxLength,omitempty"`
64 | MinLength *int64 `json:"minLength,omitempty"`
65 | Pattern string `json:"pattern,omitempty"`
66 |
67 | // Arrays
68 | MaxItems *int64 `json:"maxItems,omitempty"`
69 | MinItems *int64 `json:"minItems,omitempty"`
70 | UniqueItems bool `json:"uniqueItems,omitempty"`
71 |
72 | // Objects
73 | MaxProperties *int64 `json:"maxProperties,omitempty"`
74 | MinProperties *int64 `json:"minProperties,omitempty"`
75 | Required []string `json:"required,omitempty"`
76 |
77 | // All
78 | Enum []Any `json:"enum,omitempty"`
79 |
80 | // The following properties are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification.
81 |
82 | // Value MUST be a string.
83 | // Multiple types via an array are not supported.
84 | Type string `json:"type,omitempty"`
85 |
86 | // Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
87 | AllOf []*Schema `json:"allOf,omitempty"`
88 |
89 | // Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
90 | OneOf []*Schema `json:"oneOf,omitempty"`
91 |
92 | // Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
93 | AnyOf []*Schema `json:"anyOf,omitempty"`
94 |
95 | // Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
96 | Not *Schema `json:"not,omitempty"`
97 |
98 | // Value MUST be an object and not an array.
99 | // Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
100 | // items MUST be present if the type is array.
101 | Items *Schema `json:"items,omitempty"`
102 |
103 | // Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
104 | Properties map[string]*Schema `json:"properties,omitempty"`
105 |
106 | // Value can be boolean or object.
107 | // Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
108 | AdditionalProperties *Schema `json:"additionalProperties,omitempty"`
109 |
110 | // CommonMark syntax MAY be used for rich text representation.
111 | Description string `json:"description,omitempty"`
112 |
113 | // See Data Type Formats for further details.
114 | // While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats.
115 | Format string `json:"format,omitempty"`
116 |
117 | // The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided.
118 | // Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level.
119 | // For example, if type is string, then default can be "foo" but cannot be 1.
120 | Default Any `json:"default,omitempty"`
121 | }
122 |
--------------------------------------------------------------------------------
/spec/schema_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // Schema It's the Union type of schema and Refable
11 | type Schema struct {
12 | Refable
13 | schema
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of schema or Refable.
17 | func (m Schema) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.schema)
22 | }
23 |
24 | // UnmarshalJSON sets schema or Refable to data.
25 | func (m *Schema) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.Schema: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.schema)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/schema_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Primitive data types in the OAS are based on the types supported by the JSON Schema Specification Wright Draft 00.
4 | // Note that integer as a type is also supported and is defined as a JSON number without a fraction or exponent part.
5 | // null is not supported as a type (see nullable for an alternative solution).
6 | // Models are defined using the Schema Object, which is an extended subset of JSON Schema Specification Wright Draft 00.
7 | const (
8 | TypeBoolean = "boolean"
9 | TypeNumber = "number"
10 | TypeInteger = "integer"
11 | TypeString = "string"
12 | TypeObject = "object"
13 | TypeArray = "array"
14 | )
15 |
16 | var timeExample = NewAny("2006-01-02T15:04:05+08:00")
17 |
18 | // BooleanProperty creates a boolean property
19 | func BooleanProperty() *Schema {
20 | so := &Schema{}
21 | so.Type = TypeBoolean
22 | return so
23 | }
24 |
25 | // Float64Property creates a float64/double property
26 | func Float64Property() *Schema {
27 | return FloatFmtProperty("double")
28 | }
29 |
30 | // Float32Property creates a float32/float property
31 | func Float32Property() *Schema {
32 | return FloatFmtProperty("float")
33 | }
34 |
35 | // FloatFmtProperty creates a property for the named float format
36 | func FloatFmtProperty(format string) *Schema {
37 | so := &Schema{}
38 | so.Type = TypeNumber
39 | so.Format = format
40 | return so
41 | }
42 |
43 | // Int8Property creates an int8 property
44 | func Int8Property() *Schema {
45 | return IntFmtProperty("int8")
46 | }
47 |
48 | // Int16Property creates an int16 property
49 | func Int16Property() *Schema {
50 | return IntFmtProperty("int16")
51 | }
52 |
53 | // Int32Property creates an int32 property
54 | func Int32Property() *Schema {
55 | return IntFmtProperty("int32")
56 | }
57 |
58 | // Int64Property creates an int64 property
59 | func Int64Property() *Schema {
60 | return IntFmtProperty("int64")
61 | }
62 |
63 | // IntFmtProperty creates a property for the named int format
64 | func IntFmtProperty(format string) *Schema {
65 | so := &Schema{}
66 | so.Type = TypeInteger
67 | so.Format = format
68 | return so
69 | }
70 |
71 | // StringProperty creates a string property
72 | func StringProperty() *Schema {
73 | return StrFmtProperty("")
74 | }
75 |
76 | // ByteProperty creates a string property base64 encoded characters.
77 | func ByteProperty() *Schema {
78 | return StrFmtProperty("byte")
79 | }
80 |
81 | // BinaryProperty creates a string property any sequence of octets.
82 | func BinaryProperty() *Schema {
83 | return StrFmtProperty("binary")
84 | }
85 |
86 | // PasswordProperty creates a string property A hint to UIs to obscure input.
87 | func PasswordProperty() *Schema {
88 | return StrFmtProperty("password")
89 | }
90 |
91 | // DateProperty creates a date property
92 | func DateProperty() *Schema {
93 | return StrFmtProperty("data").WithExample(timeExample)
94 | }
95 |
96 | // DateTimeProperty creates a date time property
97 | func DateTimeProperty() *Schema {
98 | return StrFmtProperty("data-time").WithExample(timeExample)
99 | }
100 |
101 | // StrFmtProperty creates a property for the named string format
102 | func StrFmtProperty(format string) *Schema {
103 | so := &Schema{}
104 | so.Type = TypeString
105 | so.Format = format
106 | return so
107 | }
108 |
109 | // MapProperty creates a map property
110 | func MapProperty(property *Schema) *Schema {
111 | so := &Schema{}
112 | so.Type = TypeObject
113 | so.AdditionalProperties = property
114 | return so
115 | }
116 |
117 | // ArrayProperty creates an array property
118 | func ArrayProperty(items *Schema) *Schema {
119 | so := &Schema{}
120 | so.Type = TypeArray
121 | so.Items = items
122 | return so
123 | }
124 |
125 | // AllSchema creates a schema with allOf
126 | func AllSchema(schemas ...*Schema) *Schema {
127 | so := &Schema{}
128 | so.AllOf = schemas
129 | return so
130 | }
131 |
132 | // OneSchema creates a schema with oneOf
133 | func OneSchema(schemas ...*Schema) *Schema {
134 | so := &Schema{}
135 | so.OneOf = schemas
136 | return so
137 | }
138 |
139 | // AnySchema creates a schema with anyOf
140 | func AnySchema(schemas ...*Schema) *Schema {
141 | so := &Schema{}
142 | so.AnyOf = schemas
143 | return so
144 | }
145 |
146 | // NotSchema creates a schema with not
147 | func NotSchema(schema *Schema) *Schema {
148 | so := &Schema{}
149 | so.Not = schema
150 | return so
151 | }
152 |
153 | // WithTitle sets the title for this schema, allows for chaining
154 | func (s *Schema) WithTitle(title string) *Schema {
155 | s.Title = title
156 | return s
157 | }
158 |
159 | // WithDescription sets the description for this schema, allows for chaining
160 | func (s *Schema) WithDescription(description string) *Schema {
161 | s.Description = description
162 | return s
163 | }
164 |
165 | // WithProperties sets the properties for this schema
166 | func (s *Schema) WithProperties(schemas map[string]*Schema) *Schema {
167 | s.Properties = schemas
168 | return s
169 | }
170 |
171 | // WithProperty sets a property on this schema
172 | func (s *Schema) WithProperty(name string, schema *Schema) *Schema {
173 | if s.Properties == nil {
174 | s.Properties = make(map[string]*Schema)
175 | }
176 | s.Properties[name] = schema
177 | return s
178 | }
179 |
180 | // WithAllOf sets the all of property
181 | func (s *Schema) WithAllOf(schemas ...*Schema) *Schema {
182 | s.AllOf = schemas
183 | return s
184 | }
185 |
186 | // WithMaxProperties sets the max number of properties an object can have
187 | func (s *Schema) WithMaxProperties(max int64) *Schema {
188 | s.MaxProperties = &max
189 | return s
190 | }
191 |
192 | // WithMinProperties sets the min number of properties an object must have
193 | func (s *Schema) WithMinProperties(min int64) *Schema {
194 | s.MinProperties = &min
195 | return s
196 | }
197 |
198 | // WithType sets the type of this schema for a single value item
199 | func (s *Schema) WithType(typ, format string) *Schema {
200 | s.Type = typ
201 | s.Format = format
202 | return s
203 | }
204 |
205 | // WithFormat sets the format of this schema for a single value item
206 | func (s *Schema) WithFormat(format string) *Schema {
207 | s.Format = format
208 | return s
209 | }
210 |
211 | // WithDefault sets the default value on this parameter
212 | func (s *Schema) WithDefault(defaultValue Any) *Schema {
213 | s.Default = defaultValue
214 | return s
215 | }
216 |
217 | // WithRequired flags this parameter as required
218 | func (s *Schema) WithRequired(items ...string) *Schema {
219 | s.Required = items
220 | return s
221 | }
222 |
223 | // AddRequired adds field names to the required properties array
224 | func (s *Schema) AddRequired(items ...string) *Schema {
225 | s.Required = append(s.Required, items...)
226 | return s
227 | }
228 |
229 | // WithMaxLength sets a max length value
230 | func (s *Schema) WithMaxLength(max int64) *Schema {
231 | s.MaxLength = &max
232 | return s
233 | }
234 |
235 | // WithMinLength sets a min length value
236 | func (s *Schema) WithMinLength(min int64) *Schema {
237 | s.MinLength = &min
238 | return s
239 | }
240 |
241 | // WithPattern sets a pattern value
242 | func (s *Schema) WithPattern(pattern string) *Schema {
243 | s.Pattern = pattern
244 | return s
245 | }
246 |
247 | // WithMultipleOf sets a multiple of value
248 | func (s *Schema) WithMultipleOf(number float64) *Schema {
249 | s.MultipleOf = &number
250 | return s
251 | }
252 |
253 | // WithMaximum sets a maximum number value
254 | func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema {
255 | s.Maximum = &max
256 | s.ExclusiveMaximum = exclusive
257 | return s
258 | }
259 |
260 | // WithMinimum sets a minimum number value
261 | func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema {
262 | s.Minimum = &min
263 | s.ExclusiveMinimum = exclusive
264 | return s
265 | }
266 |
267 | // WithEnum sets a the enum values (replace)
268 | func (s *Schema) WithEnum(values ...Any) *Schema {
269 | s.Enum = values
270 | return s
271 | }
272 |
273 | // WithMaxItems sets the max items
274 | func (s *Schema) WithMaxItems(size int64) *Schema {
275 | s.MaxItems = &size
276 | return s
277 | }
278 |
279 | // WithMinItems sets the min items
280 | func (s *Schema) WithMinItems(size int64) *Schema {
281 | s.MinItems = &size
282 | return s
283 | }
284 |
285 | // UniqueValues dictates that this array can only have unique items
286 | func (s *Schema) UniqueValues() *Schema {
287 | s.UniqueItems = true
288 | return s
289 | }
290 |
291 | // AllowDuplicates this array can have duplicates
292 | func (s *Schema) AllowDuplicates() *Schema {
293 | s.UniqueItems = false
294 | return s
295 | }
296 |
297 | // AddToAllOf adds a schema to the allOf property
298 | func (s *Schema) AddToAllOf(schemas ...*Schema) *Schema {
299 | s.AllOf = append(s.AllOf, schemas...)
300 | return s
301 | }
302 |
303 | // AsReadOnly flags this schema as readonly
304 | func (s *Schema) AsReadOnly() *Schema {
305 | s.ReadOnly = true
306 | return s
307 | }
308 |
309 | // AsWritable flags this schema as writeable (not read-only)
310 | func (s *Schema) AsWritable() *Schema {
311 | s.ReadOnly = false
312 | return s
313 | }
314 |
315 | // WithExample sets the example for this schema
316 | func (s *Schema) WithExample(example Any) *Schema {
317 | s.Example = example
318 | return s
319 | }
320 |
321 | // WithExternalDocs sets/removes the external docs for/from this schema.
322 | // When you pass empty strings as params the external documents will be removed.
323 | // When you pass non-empty string as one value then those values will be used on the external docs object.
324 | // So when you pass a non-empty description, you should also pass the url and vice versa.
325 | func (s *Schema) WithExternalDocs(description, url string) *Schema {
326 | if description == "" && url == "" {
327 | s.ExternalDocs = nil
328 | return s
329 | }
330 |
331 | if s.ExternalDocs == nil {
332 | s.ExternalDocs = &ExternalDocumentation{}
333 | }
334 | s.ExternalDocs.Description = description
335 | s.ExternalDocs.URL = url
336 | return s
337 | }
338 |
339 | // WithXMLName sets the xml name for the object
340 | func (s *Schema) WithXMLName(name string) *Schema {
341 | if s.XML == nil {
342 | s.XML = &XML{}
343 | }
344 | s.XML.Name = name
345 | return s
346 | }
347 |
348 | // WithXMLNamespace sets the xml namespace for the object
349 | func (s *Schema) WithXMLNamespace(namespace string) *Schema {
350 | if s.XML == nil {
351 | s.XML = &XML{}
352 | }
353 | s.XML.Namespace = namespace
354 | return s
355 | }
356 |
357 | // WithXMLPrefix sets the xml prefix for the object
358 | func (s *Schema) WithXMLPrefix(prefix string) *Schema {
359 | if s.XML == nil {
360 | s.XML = &XML{}
361 | }
362 | s.XML.Prefix = prefix
363 | return s
364 | }
365 |
366 | // AsXMLAttribute flags this object as xml attribute
367 | func (s *Schema) AsXMLAttribute() *Schema {
368 | if s.XML == nil {
369 | s.XML = &XML{}
370 | }
371 | s.XML.Attribute = true
372 | return s
373 | }
374 |
375 | // AsXMLElement flags this object as an xml node
376 | func (s *Schema) AsXMLElement() *Schema {
377 | if s.XML == nil {
378 | s.XML = &XML{}
379 | }
380 | s.XML.Attribute = false
381 | return s
382 | }
383 |
384 | // AsWrappedXML flags this object as wrapped, this is mostly useful for array types
385 | func (s *Schema) AsWrappedXML() *Schema {
386 | if s.XML == nil {
387 | s.XML = &XML{}
388 | }
389 | s.XML.Wrapped = true
390 | return s
391 | }
392 |
393 | // AsUnwrappedXML flags this object as an xml node
394 | func (s *Schema) AsUnwrappedXML() *Schema {
395 | if s.XML == nil {
396 | s.XML = &XML{}
397 | }
398 | s.XML.Wrapped = false
399 | return s
400 | }
401 |
--------------------------------------------------------------------------------
/spec/security_requirement.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // SecurityRequirement Lists the required security schemes to execute this operation.
4 | // The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object.
5 | // Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized.
6 | // This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information.
7 | // When a list of Security Requirement Objects is defined on the Open API object or Operation Object, only one of Security Requirement Objects in the list needs to be satisfied to authorize the request.
8 | // Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object.
9 | // If the security scheme is of type "oauth2" or "openIdConnect", then the value is a list of scope names required for the execution.
10 | // For other security scheme types, the array MUST be empty.
11 | type SecurityRequirement []string
12 |
--------------------------------------------------------------------------------
/spec/security_scheme.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // securityScheme an API key (either as a header or as a query parameter), OAuth2's common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect Discovery.
4 | type securityScheme struct {
5 |
6 | // Any REQUIRED.
7 | // The type of the security scheme.
8 | // Valid values are "apiKey", "http", "oauth2", "openIdConnect".
9 | Type string `json:"type"`
10 |
11 | // Any A short description for security scheme.
12 | // CommonMark syntax MAY be used for rich text representation.
13 | Description string `json:"description,omitempty"`
14 |
15 | // apiKey REQUIRED.
16 | // The name of the header, query or cookie parameter to be used.
17 | Name string `json:"name,omitempty"`
18 |
19 | // apiKey REQUIRED.
20 | // The location of the API key.
21 | // Valid values are "query", "header" or "cookie".
22 | In string `json:"in,omitempty"`
23 |
24 | // http REQUIRED.
25 | // The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC7235.
26 | Scheme string `json:"scheme,omitempty"`
27 |
28 | // http ("bearer") A hint to the client to identify how the bearer token is formatted.
29 | // Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes.
30 | BearerFormat string `json:"bearerFormat,omitempty"`
31 |
32 | // oauth2 REQUIRED.
33 | // An object containing configuration information for the flow types supported.
34 | Flows *OAuthFlows `json:"flows,omitempty"`
35 |
36 | // openIdConnect REQUIRED.
37 | // OpenId Connect URL to discover OAuth2 configuration values.
38 | // This MUST be in the form of a URL.
39 | OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"`
40 | }
41 |
--------------------------------------------------------------------------------
/spec/security_scheme_or_refable.go:
--------------------------------------------------------------------------------
1 | // Code generated; DO NOT EDIT.
2 |
3 | package spec
4 |
5 | import (
6 | "encoding/json"
7 | "errors"
8 | )
9 |
10 | // SecurityScheme It's the Union type of securityScheme and Refable
11 | type SecurityScheme struct {
12 | Refable
13 | securityScheme
14 | }
15 |
16 | // MarshalJSON returns m as the JSON encoding of securityScheme or Refable.
17 | func (m SecurityScheme) MarshalJSON() ([]byte, error) {
18 | if m.Ref != "" {
19 | return json.Marshal(m.Refable)
20 | }
21 | return json.Marshal(m.securityScheme)
22 | }
23 |
24 | // UnmarshalJSON sets securityScheme or Refable to data.
25 | func (m *SecurityScheme) UnmarshalJSON(data []byte) error {
26 | if m == nil {
27 | return errors.New("spec.SecurityScheme: UnmarshalJSON on nil pointer")
28 | }
29 | if len(data) == 0 {
30 | return nil
31 | }
32 | err := json.Unmarshal(data, &m.Refable)
33 | if err != nil {
34 | return err
35 | }
36 | if m.Ref != "" {
37 | return nil
38 | }
39 | return json.Unmarshal(data, &m.securityScheme)
40 | }
41 |
--------------------------------------------------------------------------------
/spec/security_scheme_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | const (
4 | SecurityHTTP = "http"
5 | SecurityAPIKey = "apiKey"
6 | SecurityOAuth2 = "oauth2"
7 | SecurityOpenIDConnect = "openIdConnect"
8 | )
9 |
10 | // BasicAuth creates a basic auth security scheme
11 | func BasicAuth() *SecurityScheme {
12 | ss := &SecurityScheme{}
13 | ss.Type = SecurityHTTP
14 | ss.Scheme = "basic"
15 | return ss
16 | }
17 |
18 | // BearerAuth creates a bearer auth security scheme
19 | func BearerAuth(bearerFormat string) *SecurityScheme {
20 | ss := &SecurityScheme{}
21 | ss.Type = SecurityHTTP
22 | ss.Scheme = "bearer"
23 | ss.BearerFormat = bearerFormat
24 | return ss
25 | }
26 |
27 | // APIKeyAuth creates an api key auth security scheme
28 | func APIKeyAuth(fieldName, valueSource string) *SecurityScheme {
29 | ss := &SecurityScheme{}
30 | ss.Type = SecurityAPIKey
31 | ss.Name = fieldName
32 | ss.In = valueSource
33 | return ss
34 | }
35 |
36 | // OAuth2Implicit creates an implicit flow oauth2 security scheme
37 | func OAuth2Implicit(authorizationURL string) *SecurityScheme {
38 | ss := &SecurityScheme{}
39 | ss.Flows = &OAuthFlows{}
40 | ss.Type = SecurityOAuth2
41 | ss.Flows.Implicit.AuthorizationURL = authorizationURL
42 | return ss
43 | }
44 |
45 | // OAuth2Password creates a password flow oauth2 security scheme
46 | func OAuth2Password(tokenURL string) *SecurityScheme {
47 | ss := &SecurityScheme{}
48 | ss.Flows = &OAuthFlows{}
49 | ss.Type = SecurityOAuth2
50 | ss.Flows.Password.TokenURL = tokenURL
51 | return ss
52 | }
53 |
54 | // OAuth2AuthorizationCode creates an application flow oauth2 security scheme
55 | func OAuth2AuthorizationCode(tokenURL string) *SecurityScheme {
56 | ss := &SecurityScheme{}
57 | ss.Flows = &OAuthFlows{}
58 | ss.Type = SecurityOAuth2
59 | ss.Flows.AuthorizationCode.TokenURL = tokenURL
60 | return ss
61 | }
62 |
63 | // OAuth2ClientCredentials creates an access token flow oauth2 security scheme
64 | func OAuth2ClientCredentials(authorizationURL, tokenURL string) *SecurityScheme {
65 | ss := &SecurityScheme{}
66 | ss.Flows = &OAuthFlows{}
67 | ss.Type = SecurityOAuth2
68 | ss.Flows.ClientCredentials.AuthorizationURL = authorizationURL
69 | ss.Flows.ClientCredentials.TokenURL = tokenURL
70 | return ss
71 | }
72 |
--------------------------------------------------------------------------------
/spec/server.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Server An object representing a Server.
4 | type Server struct {
5 |
6 | // REQUIRED.
7 | // A URL to the target host.
8 | // 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.
9 | // Variable substitutions will be made when a variable is named in {brackets}.
10 | URL string `json:"url"`
11 |
12 | // An optional string describing the host designated by the URL.
13 | // CommonMark syntax MAY be used for rich text representation.
14 | Description string `json:"description,omitempty"`
15 |
16 | // A map between a variable name and its value.
17 | // The value is used for substitution in the server's URL template.
18 | Variables map[string]*ServerVariable `json:"variables,omitempty"`
19 | }
20 |
--------------------------------------------------------------------------------
/spec/server_util.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | import (
4 | "net/url"
5 | "sort"
6 | )
7 |
8 | // NewServers Will list all possible server options based on all servers
9 | func NewServers(uris ...string) ([]*Server, error) {
10 | uris = append(uris, "/")
11 | uris = removeDuplicates(uris)
12 | ss := []*Server{}
13 | for _, v := range uris {
14 | ss = append(ss, &Server{
15 | URL: v,
16 | })
17 | }
18 |
19 | schemes := []string{"http://", "https://"}
20 | hosts := []string{"localhost"}
21 | paths := []string{"/"}
22 | ports := []string{""}
23 | for _, v := range uris {
24 | uri, err := url.Parse(v)
25 | if err != nil {
26 | return nil, err
27 | }
28 |
29 | if host := uri.Hostname(); host != "" {
30 | hosts = append(hosts, host)
31 | }
32 |
33 | if uri.Path != "" {
34 | paths = append(paths, uri.Path)
35 | }
36 |
37 | if port := uri.Port(); port != "" {
38 | ports = append(ports, ":"+port)
39 | }
40 | }
41 | hosts = removeDuplicates(hosts)
42 | ports = removeDuplicates(ports)
43 | paths = removeDuplicates(paths)
44 | ss = append(ss, &Server{
45 | URL: "{scheme}{host}{port}{path}",
46 | Variables: map[string]*ServerVariable{
47 | "scheme": &ServerVariable{
48 | Enum: schemes,
49 | Default: schemes[0],
50 | },
51 | "host": &ServerVariable{
52 | Enum: hosts,
53 | Default: hosts[0],
54 | },
55 | "port": &ServerVariable{
56 | Enum: ports,
57 | Default: ports[0],
58 | },
59 | "path": &ServerVariable{
60 | Enum: paths,
61 | Default: paths[0],
62 | },
63 | },
64 | })
65 | return ss, nil
66 | }
67 |
68 | func removeDuplicates(a []string) []string {
69 | if len(a) <= 1 {
70 | return a
71 | }
72 | sort.Strings(a)
73 | ret := []string{a[0]}
74 | for i := 1; i != len(a); i++ {
75 | if a[i-1] != a[i] {
76 | ret = append(ret, a[i])
77 | }
78 | }
79 | return ret
80 | }
81 |
--------------------------------------------------------------------------------
/spec/server_variable.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // ServerVariable An object representing a Server Variable for server URL template substitution.
4 | type ServerVariable struct {
5 |
6 | // An enumeration of string values to be used if the substitution options are from a limited set.
7 | Enum []string `json:"enum,omitempty"`
8 |
9 | // REQUIRED.
10 | // The default value to use for substitution, and to send, if an alternate value is not supplied.
11 | // Unlike the Schema Object's default, this value MUST be provided by the consumer.
12 | Default string `json:"default"`
13 |
14 | // An optional description for the server variable.
15 | // CommonMark syntax MAY be used for rich text representation.
16 | Description string `json:"description,omitempty"`
17 | }
18 |
--------------------------------------------------------------------------------
/spec/tag.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // Tag Adds metadata to a single tag that is used by the Operation Object.
4 | // It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
5 | type Tag struct {
6 |
7 | // REQUIRED.
8 | // The name of the tag.
9 | Name string `json:"name"`
10 |
11 | // A short description for the tag.
12 | // CommonMark syntax MAY be used for rich text representation.
13 | Description string `json:"description,omitempty"`
14 |
15 | // Additional external documentation for this tag
16 | ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
17 | }
18 |
--------------------------------------------------------------------------------
/spec/testdata/api-with-examples.yaml:
--------------------------------------------------------------------------------
1 | openapi: "3.0.0"
2 | info:
3 | title: Simple API overview
4 | version: v2
5 | paths:
6 | /:
7 | get:
8 | operationId: listVersionsv2
9 | summary: List API versions
10 | responses:
11 | '200':
12 | description: |-
13 | 200 response
14 | content:
15 | application/json:
16 | examples:
17 | foo:
18 | value: {
19 | "versions": [
20 | {
21 | "status": "CURRENT",
22 | "updated": "2011-01-21T11:33:21Z",
23 | "id": "v2.0",
24 | "links": [
25 | {
26 | "href": "http://127.0.0.1:8774/v2/",
27 | "rel": "self"
28 | }
29 | ]
30 | },
31 | {
32 | "status": "EXPERIMENTAL",
33 | "updated": "2013-07-23T11:33:21Z",
34 | "id": "v3.0",
35 | "links": [
36 | {
37 | "href": "http://127.0.0.1:8774/v3/",
38 | "rel": "self"
39 | }
40 | ]
41 | }
42 | ]
43 | }
44 | '300':
45 | description: |-
46 | 300 response
47 | content:
48 | application/json:
49 | examples:
50 | foo:
51 | value: |
52 | {
53 | "versions": [
54 | {
55 | "status": "CURRENT",
56 | "updated": "2011-01-21T11:33:21Z",
57 | "id": "v2.0",
58 | "links": [
59 | {
60 | "href": "http://127.0.0.1:8774/v2/",
61 | "rel": "self"
62 | }
63 | ]
64 | },
65 | {
66 | "status": "EXPERIMENTAL",
67 | "updated": "2013-07-23T11:33:21Z",
68 | "id": "v3.0",
69 | "links": [
70 | {
71 | "href": "http://127.0.0.1:8774/v3/",
72 | "rel": "self"
73 | }
74 | ]
75 | }
76 | ]
77 | }
78 | /v2:
79 | get:
80 | operationId: getVersionDetailsv2
81 | summary: Show API version details
82 | responses:
83 | '200':
84 | description: |-
85 | 200 response
86 | content:
87 | application/json:
88 | examples:
89 | foo:
90 | value: {
91 | "version": {
92 | "status": "CURRENT",
93 | "updated": "2011-01-21T11:33:21Z",
94 | "media-types": [
95 | {
96 | "base": "application/xml",
97 | "type": "application/vnd.openstack.compute+xml;version=2"
98 | },
99 | {
100 | "base": "application/json",
101 | "type": "application/vnd.openstack.compute+json;version=2"
102 | }
103 | ],
104 | "id": "v2.0",
105 | "links": [
106 | {
107 | "href": "http://127.0.0.1:8774/v2/",
108 | "rel": "self"
109 | },
110 | {
111 | "href": "http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf",
112 | "type": "application/pdf",
113 | "rel": "describedby"
114 | },
115 | {
116 | "href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl",
117 | "type": "application/vnd.sun.wadl+xml",
118 | "rel": "describedby"
119 | },
120 | {
121 | "href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl",
122 | "type": "application/vnd.sun.wadl+xml",
123 | "rel": "describedby"
124 | }
125 | ]
126 | }
127 | }
128 | '203':
129 | description: |-
130 | 203 response
131 | content:
132 | application/json:
133 | examples:
134 | foo:
135 | value: {
136 | "version": {
137 | "status": "CURRENT",
138 | "updated": "2011-01-21T11:33:21Z",
139 | "media-types": [
140 | {
141 | "base": "application/xml",
142 | "type": "application/vnd.openstack.compute+xml;version=2"
143 | },
144 | {
145 | "base": "application/json",
146 | "type": "application/vnd.openstack.compute+json;version=2"
147 | }
148 | ],
149 | "id": "v2.0",
150 | "links": [
151 | {
152 | "href": "http://23.253.228.211:8774/v2/",
153 | "rel": "self"
154 | },
155 | {
156 | "href": "http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf",
157 | "type": "application/pdf",
158 | "rel": "describedby"
159 | },
160 | {
161 | "href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl",
162 | "type": "application/vnd.sun.wadl+xml",
163 | "rel": "describedby"
164 | }
165 | ]
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/spec/testdata/callback-example.yaml:
--------------------------------------------------------------------------------
1 | openapi: 3.0.0
2 | info:
3 | title: Callback Example
4 | version: 1.0.0
5 | paths:
6 | /streams:
7 | post:
8 | description: subscribes a client to receive out-of-band data
9 | parameters:
10 | - name: callbackUrl
11 | in: query
12 | required: true
13 | description: |
14 | the location where data will be sent. Must be network accessible
15 | by the source server
16 | schema:
17 | type: string
18 | format: uri
19 | example: https://tonys-server.com
20 | responses:
21 | '201':
22 | description: subscription successfully created
23 | content:
24 | application/json:
25 | schema:
26 | description: subscription information
27 | required:
28 | - subscriptionId
29 | properties:
30 | subscriptionId:
31 | description: this unique identifier allows management of the subscription
32 | type: string
33 | example: 2531329f-fb09-4ef7-887e-84e648214436
34 | callbacks:
35 | # the name `onData` is a convenience locator
36 | onData:
37 | # when data is sent, it will be sent to the `callbackUrl` provided
38 | # when making the subscription PLUS the suffix `/data`
39 | '{$request.query.callbackUrl}/data':
40 | post:
41 | requestBody:
42 | description: subscription payload
43 | content:
44 | application/json:
45 | schema:
46 | properties:
47 | timestamp:
48 | type: string
49 | format: date-time
50 | userData:
51 | type: string
52 | responses:
53 | '202':
54 | description: |
55 | Your server implementation should return this HTTP status code
56 | if the data was received successfully
57 | '204':
58 | description: |
59 | Your server should return this HTTP status code if no longer interested
60 | in further updates
61 |
--------------------------------------------------------------------------------
/spec/testdata/link-example.yaml:
--------------------------------------------------------------------------------
1 | openapi: 3.0.0
2 | info:
3 | title: Link Example
4 | version: 1.0.0
5 | paths:
6 | /2.0/users/{username}:
7 | get:
8 | operationId: getUserByName
9 | parameters:
10 | - name: username
11 | in: path
12 | required: true
13 | schema:
14 | type: string
15 | responses:
16 | '200':
17 | description: The User
18 | content:
19 | application/json:
20 | schema:
21 | $ref: '#/components/schemas/user'
22 | links:
23 | userRepositories:
24 | $ref: '#/components/links/UserRepositories'
25 | /2.0/repositories/{username}:
26 | get:
27 | operationId: getRepositoriesByOwner
28 | parameters:
29 | - name: username
30 | in: path
31 | required: true
32 | schema:
33 | type: string
34 | responses:
35 | '200':
36 | description: repositories owned by the supplied user
37 | content:
38 | application/json:
39 | schema:
40 | type: array
41 | items:
42 | $ref: '#/components/schemas/repository'
43 | links:
44 | userRepository:
45 | $ref: '#/components/links/UserRepository'
46 | /2.0/repositories/{username}/{slug}:
47 | get:
48 | operationId: getRepository
49 | parameters:
50 | - name: username
51 | in: path
52 | required: true
53 | schema:
54 | type: string
55 | - name: slug
56 | in: path
57 | required: true
58 | schema:
59 | type: string
60 | responses:
61 | '200':
62 | description: The repository
63 | content:
64 | application/json:
65 | schema:
66 | $ref: '#/components/schemas/repository'
67 | links:
68 | repositoryPullRequests:
69 | $ref: '#/components/links/RepositoryPullRequests'
70 | /2.0/repositories/{username}/{slug}/pullrequests:
71 | get:
72 | operationId: getPullRequestsByRepository
73 | parameters:
74 | - name: username
75 | in: path
76 | required: true
77 | schema:
78 | type: string
79 | - name: slug
80 | in: path
81 | required: true
82 | schema:
83 | type: string
84 | - name: state
85 | in: query
86 | schema:
87 | type: string
88 | enum:
89 | - open
90 | - merged
91 | - declined
92 | responses:
93 | '200':
94 | description: an array of pull request objects
95 | content:
96 | application/json:
97 | schema:
98 | type: array
99 | items:
100 | $ref: '#/components/schemas/pullrequest'
101 | /2.0/repositories/{username}/{slug}/pullrequests/{pid}:
102 | get:
103 | operationId: getPullRequestsById
104 | parameters:
105 | - name: username
106 | in: path
107 | required: true
108 | schema:
109 | type: string
110 | - name: slug
111 | in: path
112 | required: true
113 | schema:
114 | type: string
115 | - name: pid
116 | in: path
117 | required: true
118 | schema:
119 | type: string
120 | responses:
121 | '200':
122 | description: a pull request object
123 | content:
124 | application/json:
125 | schema:
126 | $ref: '#/components/schemas/pullrequest'
127 | links:
128 | pullRequestMerge:
129 | $ref: '#/components/links/PullRequestMerge'
130 | /2.0/repositories/{username}/{slug}/pullrequests/{pid}/merge:
131 | post:
132 | operationId: mergePullRequest
133 | parameters:
134 | - name: username
135 | in: path
136 | required: true
137 | schema:
138 | type: string
139 | - name: slug
140 | in: path
141 | required: true
142 | schema:
143 | type: string
144 | - name: pid
145 | in: path
146 | required: true
147 | schema:
148 | type: string
149 | responses:
150 | '204':
151 | description: the PR was successfully merged
152 | components:
153 | links:
154 | UserRepositories:
155 | # returns array of '#/components/schemas/repository'
156 | operationId: getRepositoriesByOwner
157 | parameters:
158 | username: $response.body#/username
159 | UserRepository:
160 | # returns '#/components/schemas/repository'
161 | operationId: getRepository
162 | parameters:
163 | username: $response.body#/owner/username
164 | slug: $response.body#/slug
165 | RepositoryPullRequests:
166 | # returns '#/components/schemas/pullrequest'
167 | operationId: getPullRequestsByRepository
168 | parameters:
169 | username: $response.body#/owner/username
170 | slug: $response.body#/slug
171 | PullRequestMerge:
172 | # executes /2.0/repositories/{username}/{slug}/pullrequests/{pid}/merge
173 | operationId: mergePullRequest
174 | parameters:
175 | username: $response.body#/author/username
176 | slug: $response.body#/repository/slug
177 | pid: $response.body#/id
178 | schemas:
179 | user:
180 | type: object
181 | properties:
182 | username:
183 | type: string
184 | uuid:
185 | type: string
186 | repository:
187 | type: object
188 | properties:
189 | slug:
190 | type: string
191 | owner:
192 | $ref: '#/components/schemas/user'
193 | pullrequest:
194 | type: object
195 | properties:
196 | id:
197 | type: integer
198 | title:
199 | type: string
200 | repository:
201 | $ref: '#/components/schemas/repository'
202 | author:
203 | $ref: '#/components/schemas/user'
204 |
--------------------------------------------------------------------------------
/spec/testdata/petstore-expanded.yaml:
--------------------------------------------------------------------------------
1 | openapi: "3.0.0"
2 | info:
3 | version: 1.0.0
4 | title: Swagger Petstore
5 | description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification
6 | termsOfService: http://swagger.io/terms/
7 | contact:
8 | name: Swagger API Team
9 | email: apiteam@swagger.io
10 | url: http://swagger.io
11 | license:
12 | name: Apache 2.0
13 | url: https://www.apache.org/licenses/LICENSE-2.0.html
14 | servers:
15 | - url: http://petstore.swagger.io/api
16 | paths:
17 | /pets:
18 | get:
19 | description: |
20 | Returns all pets from the system that the user has access to
21 | Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
22 |
23 | Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
24 | operationId: findPets
25 | parameters:
26 | - name: tags
27 | in: query
28 | description: tags to filter by
29 | required: false
30 | style: form
31 | schema:
32 | type: array
33 | items:
34 | type: string
35 | - name: limit
36 | in: query
37 | description: maximum number of results to return
38 | required: false
39 | schema:
40 | type: integer
41 | format: int32
42 | responses:
43 | '200':
44 | description: pet response
45 | content:
46 | application/json:
47 | schema:
48 | type: array
49 | items:
50 | $ref: '#/components/schemas/Pet'
51 | default:
52 | description: unexpected error
53 | content:
54 | application/json:
55 | schema:
56 | $ref: '#/components/schemas/Error'
57 | post:
58 | description: Creates a new pet in the store. Duplicates are allowed
59 | operationId: addPet
60 | requestBody:
61 | description: Pet to add to the store
62 | required: true
63 | content:
64 | application/json:
65 | schema:
66 | $ref: '#/components/schemas/NewPet'
67 | responses:
68 | '200':
69 | description: pet response
70 | content:
71 | application/json:
72 | schema:
73 | $ref: '#/components/schemas/Pet'
74 | default:
75 | description: unexpected error
76 | content:
77 | application/json:
78 | schema:
79 | $ref: '#/components/schemas/Error'
80 | /pets/{id}:
81 | get:
82 | description: Returns a user based on a single ID, if the user does not have access to the pet
83 | operationId: find pet by id
84 | parameters:
85 | - name: id
86 | in: path
87 | description: ID of pet to fetch
88 | required: true
89 | schema:
90 | type: integer
91 | format: int64
92 | responses:
93 | '200':
94 | description: pet response
95 | content:
96 | application/json:
97 | schema:
98 | $ref: '#/components/schemas/Pet'
99 | default:
100 | description: unexpected error
101 | content:
102 | application/json:
103 | schema:
104 | $ref: '#/components/schemas/Error'
105 | delete:
106 | description: deletes a single pet based on the ID supplied
107 | operationId: deletePet
108 | parameters:
109 | - name: id
110 | in: path
111 | description: ID of pet to delete
112 | required: true
113 | schema:
114 | type: integer
115 | format: int64
116 | responses:
117 | '204':
118 | description: pet deleted
119 | default:
120 | description: unexpected error
121 | content:
122 | application/json:
123 | schema:
124 | $ref: '#/components/schemas/Error'
125 | components:
126 | schemas:
127 | Pet:
128 | allOf:
129 | - $ref: '#/components/schemas/NewPet'
130 | - required:
131 | - id
132 | properties:
133 | id:
134 | type: integer
135 | format: int64
136 |
137 | NewPet:
138 | required:
139 | - name
140 | properties:
141 | name:
142 | type: string
143 | tag:
144 | type: string
145 |
146 | Error:
147 | required:
148 | - code
149 | - message
150 | properties:
151 | code:
152 | type: integer
153 | format: int32
154 | message:
155 | type: string
156 |
--------------------------------------------------------------------------------
/spec/testdata/petstore.yaml:
--------------------------------------------------------------------------------
1 | openapi: "3.0.0"
2 | info:
3 | version: 1.0.0
4 | title: Swagger Petstore
5 | license:
6 | name: MIT
7 | servers:
8 | - url: http://petstore.swagger.io/v1
9 | paths:
10 | /pets:
11 | get:
12 | summary: List all pets
13 | operationId: listPets
14 | tags:
15 | - pets
16 | parameters:
17 | - name: limit
18 | in: query
19 | description: How many items to return at one time (max 100)
20 | required: false
21 | schema:
22 | type: integer
23 | format: int32
24 | responses:
25 | '200':
26 | description: A paged array of pets
27 | headers:
28 | x-next:
29 | description: A link to the next page of responses
30 | schema:
31 | type: string
32 | content:
33 | application/json:
34 | schema:
35 | $ref: "#/components/schemas/Pets"
36 | default:
37 | description: unexpected error
38 | content:
39 | application/json:
40 | schema:
41 | $ref: "#/components/schemas/Error"
42 | post:
43 | summary: Create a pet
44 | operationId: createPets
45 | tags:
46 | - pets
47 | responses:
48 | '201':
49 | description: Null response
50 | default:
51 | description: unexpected error
52 | content:
53 | application/json:
54 | schema:
55 | $ref: "#/components/schemas/Error"
56 | /pets/{petId}:
57 | get:
58 | summary: Info for a specific pet
59 | operationId: showPetById
60 | tags:
61 | - pets
62 | parameters:
63 | - name: petId
64 | in: path
65 | required: true
66 | description: The id of the pet to retrieve
67 | schema:
68 | type: string
69 | responses:
70 | '200':
71 | description: Expected response to a valid request
72 | content:
73 | application/json:
74 | schema:
75 | $ref: "#/components/schemas/Pets"
76 | default:
77 | description: unexpected error
78 | content:
79 | application/json:
80 | schema:
81 | $ref: "#/components/schemas/Error"
82 | components:
83 | schemas:
84 | Pet:
85 | required:
86 | - id
87 | - name
88 | properties:
89 | id:
90 | type: integer
91 | format: int64
92 | name:
93 | type: string
94 | tag:
95 | type: string
96 | Pets:
97 | type: array
98 | items:
99 | $ref: "#/components/schemas/Pet"
100 | Error:
101 | required:
102 | - code
103 | - message
104 | properties:
105 | code:
106 | type: integer
107 | format: int32
108 | message:
109 | type: string
110 |
--------------------------------------------------------------------------------
/spec/testdata/uspto.yaml:
--------------------------------------------------------------------------------
1 | openapi: 3.0.0
2 | servers:
3 | - url: '{scheme}://developer.uspto.gov/ds-api'
4 | variables:
5 | scheme:
6 | description: 'The Data Set API is accessible via https and http'
7 | enum:
8 | - 'https'
9 | - 'http'
10 | default: 'https'
11 | info:
12 | description: >-
13 | The Data Set API (DSAPI) allows the public users to discover and search
14 | USPTO exported data sets. This is a generic API that allows USPTO users to
15 | make any CSV based data files searchable through API. With the help of GET
16 | call, it returns the list of data fields that are searchable. With the help
17 | of POST call, data can be fetched based on the filters on the field names.
18 | Please note that POST call is used to search the actual data. The reason for
19 | the POST call is that it allows users to specify any complex search criteria
20 | without worry about the GET size limitations as well as encoding of the
21 | input parameters.
22 | version: 1.0.0
23 | title: USPTO Data Set API
24 | contact:
25 | name: Open Data Portal
26 | url: 'https://developer.uspto.gov'
27 | email: developer@uspto.gov
28 | tags:
29 | - name: metadata
30 | description: Find out about the data sets
31 | - name: search
32 | description: Search a data set
33 | paths:
34 | /:
35 | get:
36 | tags:
37 | - metadata
38 | operationId: list-data-sets
39 | summary: List available data sets
40 | responses:
41 | '200':
42 | description: Returns a list of data sets
43 | content:
44 | application/json:
45 | schema:
46 | $ref: '#/components/schemas/dataSetList'
47 | example:
48 | {
49 | "total": 2,
50 | "apis": [
51 | {
52 | "apiKey": "oa_citations",
53 | "apiVersionNumber": "v1",
54 | "apiUrl": "https://developer.uspto.gov/ds-api/oa_citations/v1/fields",
55 | "apiDocumentationUrl": "https://developer.uspto.gov/ds-api-docs/index.html?url=https://developer.uspto.gov/ds-api/swagger/docs/oa_citations.json"
56 | },
57 | {
58 | "apiKey": "cancer_moonshot",
59 | "apiVersionNumber": "v1",
60 | "apiUrl": "https://developer.uspto.gov/ds-api/cancer_moonshot/v1/fields",
61 | "apiDocumentationUrl": "https://developer.uspto.gov/ds-api-docs/index.html?url=https://developer.uspto.gov/ds-api/swagger/docs/cancer_moonshot.json"
62 | }
63 | ]
64 | }
65 | /{dataset}/{version}/fields:
66 | get:
67 | tags:
68 | - metadata
69 | summary: >-
70 | Provides the general information about the API and the list of fields
71 | that can be used to query the dataset.
72 | description: >-
73 | This GET API returns the list of all the searchable field names that are
74 | in the oa_citations. Please see the 'fields' attribute which returns an
75 | array of field names. Each field or a combination of fields can be
76 | searched using the syntax options shown below.
77 | operationId: list-searchable-fields
78 | parameters:
79 | - name: dataset
80 | in: path
81 | description: 'Name of the dataset. In this case, the default value is oa_citations'
82 | required: true
83 | schema:
84 | type: string
85 | default: oa_citations
86 | - name: version
87 | in: path
88 | description: Version of the dataset.
89 | required: true
90 | schema:
91 | type: string
92 | default: v1
93 | responses:
94 | '200':
95 | description: >-
96 | The dataset api for the given version is found and it is accessible
97 | to consume.
98 | content:
99 | application/json:
100 | schema:
101 | type: string
102 | '404':
103 | description: >-
104 | The combination of dataset name and version is not found in the
105 | system or it is not published yet to be consumed by public.
106 | content:
107 | application/json:
108 | schema:
109 | type: string
110 | /{dataset}/{version}/records:
111 | post:
112 | tags:
113 | - search
114 | summary: >-
115 | Provides search capability for the data set with the given search
116 | criteria.
117 | description: >-
118 | This API is based on Solr/Lucense Search. The data is indexed using
119 | SOLR. This GET API returns the list of all the searchable field names
120 | that are in the Solr Index. Please see the 'fields' attribute which
121 | returns an array of field names. Each field or a combination of fields
122 | can be searched using the Solr/Lucene Syntax. Please refer
123 | https://lucene.apache.org/core/3_6_2/queryparsersyntax.html#Overview for
124 | the query syntax. List of field names that are searchable can be
125 | determined using above GET api.
126 | operationId: perform-search
127 | parameters:
128 | - name: version
129 | in: path
130 | description: Version of the dataset.
131 | required: true
132 | schema:
133 | type: string
134 | default: v1
135 | - name: dataset
136 | in: path
137 | description: 'Name of the dataset. In this case, the default value is oa_citations'
138 | required: true
139 | schema:
140 | type: string
141 | default: oa_citations
142 | responses:
143 | '200':
144 | description: successful operation
145 | content:
146 | application/json:
147 | schema:
148 | type: array
149 | items:
150 | type: object
151 | additionalProperties:
152 | type: object
153 | '404':
154 | description: No matching record found for the given criteria.
155 | requestBody:
156 | content:
157 | application/x-www-form-urlencoded:
158 | schema:
159 | type: object
160 | properties:
161 | criteria:
162 | description: >-
163 | Uses Lucene Query Syntax in the format of
164 | propertyName:value, propertyName:[num1 TO num2] and date
165 | range format: propertyName:[yyyyMMdd TO yyyyMMdd]. In the
166 | response please see the 'docs' element which has the list of
167 | record objects. Each record structure would consist of all
168 | the fields and their corresponding values.
169 | type: string
170 | default: '*:*'
171 | start:
172 | description: Starting record number. Default value is 0.
173 | type: integer
174 | default: 0
175 | rows:
176 | description: >-
177 | Specify number of rows to be returned. If you run the search
178 | with default values, in the response you will see 'numFound'
179 | attribute which will tell the number of records available in
180 | the dataset.
181 | type: integer
182 | default: 100
183 | required:
184 | - criteria
185 | components:
186 | schemas:
187 | dataSetList:
188 | type: object
189 | properties:
190 | total:
191 | type: integer
192 | apis:
193 | type: array
194 | items:
195 | type: object
196 | properties:
197 | apiKey:
198 | type: string
199 | description: To be used as a dataset parameter value
200 | apiVersionNumber:
201 | type: string
202 | description: To be used as a version parameter value
203 | apiUrl:
204 | type: string
205 | format: uriref
206 | description: "The URL describing the dataset's fields"
207 | apiDocumentationUrl:
208 | type: string
209 | format: uriref
210 | description: A URL to the API console for each API
211 |
--------------------------------------------------------------------------------
/spec/xml.go:
--------------------------------------------------------------------------------
1 | package spec
2 |
3 | // XML A metadata object that allows for more fine-tuned XML model definitions.
4 | // When using arrays, XML element names are not inferred (for singular/plural forms) and the name property SHOULD be used to add that information.
5 | // See examples for expected behavior.
6 | type XML struct {
7 |
8 | // Replaces the name of the element/attribute used for the described schema property.
9 | // When defined within items, it will affect the name of the individual XML elements within the list.
10 | // When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true.
11 | // If wrapped is false, it will be ignored.
12 | Name string `json:"name"`
13 |
14 | // The URI of the namespace definition.
15 | // Value MUST be in the form of an absolute URI.
16 | Namespace string `json:"namespace,omitempty"`
17 |
18 | // The prefix to be used for the name.
19 | Prefix string `json:"prefix,omitempty"`
20 |
21 | // Declares whether the property definition translates to an attribute instead of an element.
22 | // Default value is false.
23 | Attribute bool `json:"attribute,omitempty"`
24 |
25 | // MAY be used only for an array definition.
26 | // Signifies whether the array is wrapped (for example, ) or unwrapped ().
27 | // Default value is false.
28 | // The definition takes effect only when defined alongside type being array (outside the items).
29 | Wrapped bool `json:"wrapped,omitempty"`
30 | }
31 |
32 | // WithName sets the xml name for the object
33 | func (x *XML) WithName(name string) *XML {
34 | x.Name = name
35 | return x
36 | }
37 |
38 | // WithNamespace sets the xml namespace for the object
39 | func (x *XML) WithNamespace(namespace string) *XML {
40 | x.Namespace = namespace
41 | return x
42 | }
43 |
44 | // WithPrefix sets the xml prefix for the object
45 | func (x *XML) WithPrefix(prefix string) *XML {
46 | x.Prefix = prefix
47 | return x
48 | }
49 |
50 | // AsAttribute flags this object as xml attribute
51 | func (x *XML) AsAttribute() *XML {
52 | x.Attribute = true
53 | return x
54 | }
55 |
56 | // AsElement flags this object as an xml node
57 | func (x *XML) AsElement() *XML {
58 | x.Attribute = false
59 | return x
60 | }
61 |
62 | // AsWrapped flags this object as wrapped, this is mostly useful for array types
63 | func (x *XML) AsWrapped() *XML {
64 | x.Wrapped = true
65 | return x
66 | }
67 |
68 | // AsUnwrapped flags this object as an xml node
69 | func (x *XML) AsUnwrapped() *XML {
70 | x.Wrapped = false
71 | return x
72 | }
73 |
--------------------------------------------------------------------------------
/util/marshal.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | )
7 |
8 | // Unmarshal Decode the format supported by openapi
9 | func Unmarshal(d []byte, v interface{}) (err error) {
10 | d, err = YAML2JSON(d)
11 | if err != nil {
12 | return err
13 | }
14 | return json.Unmarshal(d, v)
15 | }
16 |
17 | // Marshal Encode the format supported by openapi
18 | func Marshal(v interface{}, format Format) (d []byte, err error) {
19 | switch format {
20 | case JSON:
21 | return json.Marshal(v)
22 | case JSONIndent:
23 | return json.MarshalIndent(v, "", " ")
24 | case YAML:
25 | d, err = json.Marshal(v)
26 | if err != nil {
27 | return nil, err
28 | }
29 | return YAML2JSON(d)
30 | }
31 | return nil, errors.New("Bad format")
32 | }
33 |
34 | // Format for openapi
35 | type Format uint8
36 |
37 | const (
38 | JSON Format = iota
39 | JSONIndent
40 | YAML
41 | )
42 |
--------------------------------------------------------------------------------
/util/merge.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "github.com/wzshiming/openapi/spec"
5 | )
6 |
7 | // Merge Added API to root
8 | func Merge(root, added *spec.OpenAPI) {
9 | for name, path := range added.Paths {
10 | rpath, ok := root.Paths[name]
11 | if !ok {
12 | root.Paths[name] = path
13 | continue
14 | }
15 |
16 | if path.Get != nil && rpath.Get == nil {
17 | rpath.Get = path.Get
18 | }
19 |
20 | if path.Post != nil && rpath.Post == nil {
21 | rpath.Post = path.Post
22 | }
23 |
24 | if path.Put != nil && rpath.Put == nil {
25 | rpath.Put = path.Put
26 | }
27 |
28 | if path.Delete != nil && rpath.Delete == nil {
29 | rpath.Delete = path.Delete
30 | }
31 |
32 | if path.Head != nil && rpath.Head == nil {
33 | rpath.Head = path.Head
34 | }
35 |
36 | if path.Options != nil && rpath.Options == nil {
37 | rpath.Options = path.Options
38 | }
39 |
40 | if path.Patch != nil && rpath.Patch == nil {
41 | rpath.Patch = path.Patch
42 | }
43 |
44 | if path.Trace != nil && rpath.Trace == nil {
45 | rpath.Trace = path.Trace
46 | }
47 | }
48 |
49 | root.Tags = append(root.Tags, added.Tags...)
50 |
51 | if added.Components != nil && root.Components == nil {
52 | root.Components = added.Components
53 | } else {
54 | rcom := root.Components
55 | com := added.Components
56 | for name, v := range com.Schemas {
57 | if _, ok := rcom.Schemas[name]; !ok {
58 | rcom.Schemas[name] = v
59 | }
60 | }
61 |
62 | for name, v := range com.Responses {
63 | if _, ok := rcom.Responses[name]; !ok {
64 | rcom.Responses[name] = v
65 | }
66 | }
67 |
68 | for name, v := range com.Parameters {
69 | if _, ok := rcom.Parameters[name]; !ok {
70 | rcom.Parameters[name] = v
71 | }
72 | }
73 |
74 | for name, v := range com.Examples {
75 | if _, ok := rcom.Examples[name]; !ok {
76 | rcom.Examples[name] = v
77 | }
78 | }
79 |
80 | for name, v := range com.RequestBodies {
81 | if _, ok := rcom.RequestBodies[name]; !ok {
82 | rcom.RequestBodies[name] = v
83 | }
84 | }
85 |
86 | for name, v := range com.Headers {
87 | if _, ok := rcom.Headers[name]; !ok {
88 | rcom.Headers[name] = v
89 | }
90 | }
91 |
92 | for name, v := range com.SecuritySchemes {
93 | if _, ok := rcom.SecuritySchemes[name]; !ok {
94 | rcom.SecuritySchemes[name] = v
95 | }
96 | }
97 |
98 | for name, v := range com.Links {
99 | if _, ok := rcom.Links[name]; !ok {
100 | rcom.Links[name] = v
101 | }
102 | }
103 |
104 | for name, v := range com.Callbacks {
105 | if _, ok := rcom.Callbacks[name]; !ok {
106 | rcom.Callbacks[name] = v
107 | }
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/util/open.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "errors"
5 | "io/ioutil"
6 | "net/http"
7 | "net/url"
8 | )
9 |
10 | // ReadFile Automatic distinction protocol switching between HTTP and local
11 | func ReadFile(path string) ([]byte, error) {
12 | u, err := url.Parse(path)
13 | if err != nil {
14 | return nil, err
15 | }
16 |
17 | switch u.Scheme {
18 | case "http", "https":
19 | resp, err := http.Get(u.String())
20 | if err != nil {
21 | return nil, err
22 | }
23 | data, err := ioutil.ReadAll(resp.Body)
24 | if err != nil {
25 | return nil, err
26 | }
27 | defer resp.Body.Close()
28 | return data, nil
29 |
30 | case "file", "":
31 | data, err := ioutil.ReadFile(u.Path)
32 | if err != nil {
33 | return nil, err
34 | }
35 | return data, nil
36 | }
37 |
38 | return nil, errors.New("error path " + path)
39 | }
40 |
--------------------------------------------------------------------------------
/util/yaml_and_json.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 |
7 | yaml "gopkg.in/yaml.v2"
8 | )
9 |
10 | func JSON2YAML(d []byte) ([]byte, error) {
11 | ms := yaml.MapSlice{}
12 | err := yaml.Unmarshal(d, &ms)
13 | if err != nil {
14 | return nil, err
15 | }
16 | return yaml.Marshal(ms)
17 | }
18 |
19 | func YAML2JSON(d []byte) ([]byte, error) {
20 | ms := yaml.MapSlice{}
21 | err := yaml.Unmarshal(d, &ms)
22 | if err != nil {
23 | return nil, err
24 | }
25 |
26 | v := yaml2json(ms)
27 | return json.MarshalIndent(v, "", " ")
28 | }
29 |
30 | func yaml2json(v interface{}) interface{} {
31 | switch t := v.(type) {
32 | case yaml.MapSlice:
33 | m := map[string]interface{}{}
34 | for _, v := range t {
35 | key := fmt.Sprint(v.Key)
36 | val := yaml2json(v.Value)
37 | m[key] = val
38 | }
39 | return m
40 | case []interface{}:
41 | for i, v := range t {
42 | t[i] = yaml2json(v)
43 | }
44 | return t
45 | default:
46 | return v
47 | }
48 | }
49 |
--------------------------------------------------------------------------------