openapi

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2024 License: MIT Imports: 11 Imported by: 0

README

GoOpenAPI

A Go Lang SDK to help create OpenApi 3.0.3 Spec

OpenAPI spec

codecov

Getting Started

import (
    _ "embed"
    
    "github.com/hydronica/go-openapi"
)

// go:embed base.json 
var base string 
func main() {

    // create doc from base template
    doc, err := openapi.NewFromJson(base)
    if err != nil {
        log.Fatal(err) 
    }
    
    // create doc from scratch
    doc = openapi.New("title", "v1.0.0", "all about this API") 
   
    doc.AddRoute(
        openapi.NewRoute("/path/v1", "GET").
            AddResponse(
                openapi.Resp{Code: 200, Desc:"valid response"}.WithJSONString('{"status":"ok"}'
                ). 
            AddRequest(
                openapi.Req{MType: "application/json", Desc:"pull data"}.
                    WithParams(myStruct)
                )
    ) 
   
   // print generated json document
   fmt.Println(string(doc.JSON()))
}
Overview

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanPath added in v0.2.0

func CleanPath(path string) string

CleanPath will convert of go path like :var into an approved openID path {var}

Types

type Code added in v0.1.6

type Code int

Code a valid https status such as '200', '201', '400', 'default'

const DefaultStatus Code = 0

func (Code) MarshalText added in v0.2.0

func (c Code) MarshalText() ([]byte, error)

func (*Code) UnmarshalText added in v0.2.0

func (c *Code) UnmarshalText(b []byte) error

type Components

type Components struct {
	Schemas map[string]Schema `json:"schemas,omitempty"`
}

type Contact

type Contact struct {
	Name  string `json:"name"`  // The identifying name of the contact person/organization.
	URL   string `json:"url"`   // The URL pointing to the contact information. MUST be in the format of a URL.
	Email string `json:"email"` // The email address of the contact person/organization. MUST be in the format of an email address.
}

type Content added in v0.1.6

type Content map[MIMEType]Media

type Encoding added in v0.1.9

type Encoding struct {
	ContentType string `json:"contentType,omitempty"` // The Content-Type for encoding a specific property.
	// headers  map[string]headerObject :  not implemented needed if media is multipart
	Style string `json:"style"` // Describes how a specific property value will be serialized depending on its type.

}

type Example added in v0.1.9

type Example struct {
	Summary string `json:"summary,omitempty"`     // Short description for the example.
	Desc    string `json:"description,omitempty"` // Long description for the example. CommonMark syntax MAY be used for rich text representation.
	//ExternalValue string `json:"externalValue,omitempty"` // A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The value field and externalValue field are mutually exclusive.
	Value any `json:"value"` // Embedded literal example. The value field and externalValue field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary.
}

Example object MAY be extended with Specification Extensions.

type ExternalDocs

type ExternalDocs struct {
	Desc string `json:"description,omitempty""`        // A short description of the target documentation. CommonMark syntax MAY be used for rich text representation.
	URL  string `json:"url,omitempty" required:"true"` // REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL.
}

type Info

type Info struct {
	Title   string   `json:"title"`                    // REQUIRED. The title of the API.
	Version string   `json:"version" required:"true"`  // REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).
	Desc    string   `json:"description"`              // A short description of the API. CommonMark syntax MAY be used for rich text representation.
	Terms   string   `json:"termsOfService,omitempty"` // A URL to the Terms of Service for the API. MUST be in the format of a URL.
	Contact *Contact `json:"contact,omitempty"`        // The contact information for the exposed API.
	License *License `json:"license,omitempty"`        // The license information for the exposed API.
}

type License

type License struct {
	Name string `json:"name"` // REQUIRED. The license name used for the API.
	URL  string `json:"url"`  // A URL to the license used for the API. MUST be in the format of a URL.
}

type MIMEType

type MIMEType string
const (
	Json    MIMEType = "application/json"
	Xml     MIMEType = "application/xml"
	Text    MIMEType = "text/plain"
	General MIMEType = "application/octet-stream"
	Html    MIMEType = "text/html"
	XForm   MIMEType = "application/x-www-form-urlencoded"
	Jscript MIMEType = "application/javascript"
	Form    MIMEType = "multipart/form-data"
)

common media types

type Media

type Media struct {
	Schema Schema `json:"schema,omitempty"` // The schema defining the content of the request, response, or parameter.
	// Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema which contains an example, the examples value SHALL override the example provided by the schema.
	Examples map[string]Example `json:"examples,omitempty"`
}

func (*Media) AddExample added in v0.2.0

func (m *Media) AddExample(exName string, i any)

AddExample will add an example object by creating a schema based on the object i passed in. The Example name will be the title of the Schema if not provided and any description from added to the example as well.

type Method

type Method string
const (
	GET     Method = "get"
	PUT     Method = "put"
	POST    Method = "post"
	DELETE  Method = "delete"
	OPTIONS Method = "options"
	HEAD    Method = "head"
	PATCH   Method = "patch"
	TRACE   Method = "trace"
)

type OpenAPI

type OpenAPI struct {
	Version      string        `json:"openapi"`                // the  semantic version number of the OpenAPI Specification version
	Servers      []Server      `json:"servers,omitempty"`      // Array of Server Objects, which provide connectivity information to a target server.
	Info         Info          `json:"info"`                   // REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
	Tags         []Tag         `json:"tags,omitempty"`         // A list of tags used by the specification with additional metadata
	Paths        Router        `json:"paths"`                  // key= path|method
	Components   Components    `json:"components,omitempty"`   // reuseable components
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"` //Additional external documentation.
}

OpenAPI represents the definition of the openapi specification 3.0.3

func New

func New(title, version, description string) *OpenAPI
Example
type tStruct struct {
	Name string `json:"name"`
	Int  int    `json:"count"`
}

doc := New("doc", "1.0.0", "about me")
doc.GetRoute("/path/v1", "GET").
	AddResponse(
		Response{Status: 200}.WithExample(tStruct{
			Name: "apple", Int: 10,
		})).
	AddResponse(
		Response{Status: 400}.WithJSONString(`{"error":"invalid request"}`))

route := doc.GetRoute("/path/v1", "PUT")
route.AddRequest(
	RequestBody{}.WithJSONString(`{"account":"apple.com", "amount":10}`),
)
route.AddResponse(Response{Status: 200})

doc.JSON()
Output:

func NewFromJson

func NewFromJson(spec string) (api *OpenAPI, err error)

func (*OpenAPI) AddTags

func (o *OpenAPI) AddTags(t ...Tag)

func (*OpenAPI) Compile added in v0.2.0

func (o *OpenAPI) Compile() error

Compile the OpenAPI object by going through all objects and consolidating schemas and return a error of issues found

func (*OpenAPI) GetRoute added in v0.2.0

func (o *OpenAPI) GetRoute(path, method string) *Route

GetRoute associated with the path and method. create a new Route if Route was not found.

func (*OpenAPI) JSON

func (o *OpenAPI) JSON() string

JSON returns the json string value for the OpenAPI object

func (*OpenAPI) JSONBytes added in v0.2.0

func (o *OpenAPI) JSONBytes() []byte

type Param

type Param struct {
	Name string `json:"name,omitempty"`        // REQUIRED. The name of the parameter.
	Desc string `json:"description,omitempty"` // A brief description of the parameter.

	In string `json:"in"` // REQUIRED. Param Type: "query", "header", "path" or "cookie".

	Schema   *Schema            `json:"schema,omitempty"` // The schema defining the param
	Examples map[string]Example `json:"examples"`         // Examples of the parameter’s potential value.

}

Param see https://swagger.io/docs/specification/describing-parameters/ - Path /user/{id} - Query /user?role=admin - header X-MyHeader: Value - cookie

type ParamSetter added in v0.2.0

type ParamSetter func() Param

type Params

type Params map[string]Param

func (Params) List added in v0.2.0

func (p Params) List() []Param

List converts the Params map to a sorted slice

func (Params) MarshalJSON added in v0.2.0

func (p Params) MarshalJSON() ([]byte, error)

func (*Params) UnmarshalJSON added in v0.2.0

func (p *Params) UnmarshalJSON(b []byte) error

type Properties

type Properties map[string]Schema

type RequestBody

type RequestBody struct {
	Desc     string  `json:"description,omitempty"` // A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
	Content  Content `json:"content,omitempty"`     // REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
	Required bool    `json:"required,omitempty"`    // Determines if the request body is required in the request. Defaults to false.
}

RequestBody describes a single request body.

func (RequestBody) WithExample added in v0.2.0

func (r RequestBody) WithExample(i any) RequestBody

func (RequestBody) WithJSONString added in v0.2.0

func (r RequestBody) WithJSONString(s string) RequestBody

func (RequestBody) WithNamedExample added in v0.2.0

func (r RequestBody) WithNamedExample(name string, i any) RequestBody

type Response

type Response struct {
	Status Code `json:"-"`

	Desc    string  `json:"description"`       // Required A short description of the response. CommonMark syntax MAY be used for rich text representation.
	Content Content `json:"content,omitempty"` // A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it.
}

Response describes a single response from an API Operation

func (Response) WithExample added in v0.2.0

func (r Response) WithExample(i any) Response

WithExample takes a struct and adds a json Content to the Response

func (Response) WithJSONString added in v0.2.0

func (r Response) WithJSONString(s string) Response

WithJSONString takes a json string object and adds a json Content to the Response s is unmarshalled into a map to extract the key and value pairs JSONStringResp || resp.JSONString(s)

func (Response) WithNamedExample added in v0.2.0

func (r Response) WithNamedExample(name string, i any) Response

type Responses

type Responses map[Code]Response

Responses for the expected responses of an operation, maps a HTTP response code to the expected response.

type Route

type Route struct {
	Tag       []string          `json:"tags,omitempty"`
	Summary   string            `json:"summary,omitempty"`
	Responses map[Code]Response `json:"responses,omitempty"`   // [status_code]Response
	Params    Params            `json:"parameters,omitempty"`  // key reference for params. key is name of Param
	Requests  *RequestBody      `json:"requestBody,omitempty"` // key reference for requests
	// contains filtered or unexported fields
}

Route is a simplified definition for managing routes in code

func (*Route) AddParam added in v0.2.0

func (r *Route) AddParam(pType, name string, value any, desc string) *Route

AddParam adds the given type params to the route pType = path, cookie, query, header It does not validate that the name is part of the path or prevent duplicate paths from being added. every element in value if it's a slice is added as an example.

func (*Route) AddRequest added in v0.2.0

func (r *Route) AddRequest(req RequestBody) *Route

func (*Route) AddResponse added in v0.2.0

func (r *Route) AddResponse(resp Response) *Route

func (*Route) CookieParam added in v0.2.0

func (r *Route) CookieParam(name string, value any, desc string) *Route

CookieParam adds an example Path Parameter to the Route (paths)

func (*Route) CookieParams added in v0.2.0

func (r *Route) CookieParams(value any) *Route

CookieParams add multiple cookie params to the provided route. the value may be a map[string]any with any primitive type or a slice of a single type. or a struct where the fields represent the values of the param.

func (*Route) HeaderParam added in v0.2.0

func (r *Route) HeaderParam(name string, value any, desc string) *Route

HeaderParam adds an example Path Parameter to the Route (paths)

func (*Route) HeaderParams added in v0.2.0

func (r *Route) HeaderParams(value any) *Route

HeaderParams add multiple header params to the provided route. the value may be a map[string]any with any primitive type or a slice of a single type. or a struct where the fields represent the values of the param.

func (*Route) PathParam added in v0.2.0

func (r *Route) PathParam(name string, value any, desc string) *Route

PathParam adds an example Path Parameter to the Route (paths)

func (*Route) PathParams added in v0.2.0

func (r *Route) PathParams(value any) *Route

PathParams add multiple path params to the provided route. the value may be a map[string]any with any primitive type or a slice of a single type. or a struct where the fields represent the values of the param.

func (*Route) QueryParam added in v0.2.0

func (r *Route) QueryParam(name string, value any, desc string) *Route

QueryParam adds an example Path Parameter to the Route (paths)

func (*Route) QueryParams added in v0.2.0

func (r *Route) QueryParams(value any) *Route

QueryParams add multiple query params to the provided route. the value may be a map[string]any with any primitive type or a slice of a single type. or a struct where the fields represent the values of the param.

func (*Route) Tags added in v0.2.0

func (r *Route) Tags(tag ...string) *Route

type Router added in v0.2.0

type Router map[string]*Route

Router key is path|method

func (Router) MarshalJSON added in v0.2.0

func (r Router) MarshalJSON() ([]byte, error)

func (Router) UnmarshalJSON added in v0.2.0

func (r Router) UnmarshalJSON(b []byte) error

type Schema

type Schema struct {
	Title string `json:"title,omitempty"`
	Type  Type   `json:"type,omitempty"`
	//Format string `json:"format,omitempty"`
	Desc string `json:"description,omitempty"`

	// Enum []string
	// Default any
	// Pattern string
	// Example any
	Items *Schema `json:"items,omitempty"`
	Ref   string  `json:"$ref,omitempty"` // link to object, #/components/schemas/{object}

	// Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
	Properties map[string]Schema `json:"properties,omitempty"`
}

Schema Object defines data types. objects (structs), maps, primitives and arrays This object is an extended subset of the JSON Schema Specification

type Server

type Server struct {
	URL  string               `json:"url"`                 // REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}.
	Desc string               `json:"description"`         // An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.
	Vars map[string]ServerVar `json:"variables,omitempty"` // A map between a variable name and its value. The value is used for substitution in the server's URL template.
}

type ServerVar

type ServerVar struct {
	Enum    []string `json:"enum"`        // An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty.
	Default string   `json:"default"`     // REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is not supplied. Note this behavior is different than the Schema Object's treatment of default values, because in those cases parameter values are optional. If the enum is defined, the value SHOULD exist in the enum's values.
	Desc    string   `json:"description"` // An optional description for the server variable. CommonMark syntax MAY be used for rich text representation.
}

type Tag

type Tag struct {
	Name         string        `json:"name" required:"true"`   // REQUIRED. The name of the tag.
	Desc         string        `json:"description"`            // A short description for the tag. CommonMark syntax MAY be used for rich text representation.
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"` // Additional external documentation for this tag.
}

type Time added in v0.1.8

type Time struct {
	time.Time
	Format string
}

func (Time) MarshalJSON added in v0.1.8

func (t Time) MarshalJSON() (data []byte, err error)

func (Time) MarshalText added in v0.1.8

func (t Time) MarshalText() ([]byte, error)

func (*Time) UnmarshalJSON added in v0.1.8

func (t *Time) UnmarshalJSON(data []byte) error

func (*Time) UnmarshalText added in v0.1.8

func (t *Time) UnmarshalText(data []byte) error

type Type

type Type string
const (
	Integer Type = "integer"
	Number  Type = "number"
	String  Type = "string"
	Boolean Type = "boolean"
	Object  Type = "object"
	Array   Type = "array"
)

Jump to

Keyboard shortcuts

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