openapi

package module
v0.2.50 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2024 License: MIT Imports: 5 Imported by: 21

README

OpenAPI structures for Go

This library provides Go structures to marshal/unmarshal and reflect OpenAPI Schema documents.

For automated HTTP REST service framework built with this library please check github.com/swaggest/rest.

Build Status Coverage Status GoDevDoc time tracker Code lines Comments

Features

  • Type safe mapping of OpenAPI 3 documents with Go structures generated from schema.
  • Type-based reflection of Go structures to OpenAPI 3.0 or 3.1 schema.
  • Schema control with field tags
    • json for request bodies and responses in JSON
    • query, path for parameters in URL
    • header, cookie, formData, file for other parameters
    • form acts as query and formData
    • field tags named after JSON Schema/OpenAPI 3 Schema constraints
    • collectionFormat to unpack slices from string
      • csv comma-separated values,
      • ssv space-separated values,
      • pipes pipe-separated values (|),
      • multi ampersand-separated values (&),
      • json additionally to slices unpacks maps and structs,
  • Flexible schema control with jsonschema-go

Example

Other examples.

reflector := openapi3.Reflector{}
reflector.Spec = &openapi3.Spec{Openapi: "3.0.3"}
reflector.Spec.Info.
    WithTitle("Things API").
    WithVersion("1.2.3").
    WithDescription("Put something here")

type req struct {
    ID     string `path:"id" example:"XXX-XXXXX"`
    Locale string `query:"locale" pattern:"^[a-z]{2}-[A-Z]{2}$"`
    Title  string `json:"string"`
    Amount uint   `json:"amount"`
    Items  []struct {
        Count uint   `json:"count"`
        Name  string `json:"name"`
    } `json:"items"`
}

type resp struct {
    ID     string `json:"id" example:"XXX-XXXXX"`
    Amount uint   `json:"amount"`
    Items  []struct {
        Count uint   `json:"count"`
        Name  string `json:"name"`
    } `json:"items"`
    UpdatedAt time.Time `json:"updated_at"`
}

putOp := openapi3.Operation{}

handleError(reflector.SetRequest(&putOp, new(req), http.MethodPut))
handleError(reflector.SetJSONResponse(&putOp, new(resp), http.StatusOK))
handleError(reflector.SetJSONResponse(&putOp, new([]resp), http.StatusConflict))
handleError(reflector.Spec.AddOperation(http.MethodPut, "/things/{id}", putOp))

getOp := openapi3.Operation{}

handleError(reflector.SetRequest(&getOp, new(req), http.MethodGet))
handleError(reflector.SetJSONResponse(&getOp, new(resp), http.StatusOK))
handleError(reflector.Spec.AddOperation(http.MethodGet, "/things/{id}", getOp))

schema, err := reflector.Spec.MarshalYAML()
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(schema))

Output:

openapi: 3.0.3
info:
  description: Put something here
  title: Things API
  version: 1.2.3
paths:
  /things/{id}:
    get:
      parameters:
      - in: query
        name: locale
        schema:
          pattern: ^[a-z]{2}-[A-Z]{2}$
          type: string
      - in: path
        name: id
        required: true
        schema:
          example: XXX-XXXXX
          type: string
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Openapi3TestResp'
          description: OK
    put:
      parameters:
      - in: query
        name: locale
        schema:
          pattern: ^[a-z]{2}-[A-Z]{2}$
          type: string
      - in: path
        name: id
        required: true
        schema:
          example: XXX-XXXXX
          type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Openapi3TestReq'
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Openapi3TestResp'
          description: OK
        "409":
          content:
            application/json:
              schema:
                items:
                  $ref: '#/components/schemas/Openapi3TestResp'
                type: array
          description: Conflict
components:
  schemas:
    Openapi3TestReq:
      properties:
        amount:
          minimum: 0
          type: integer
        items:
          items:
            properties:
              count:
                minimum: 0
                type: integer
              name:
                type: string
            type: object
          type: array
        string:
          type: string
      type: object
    Openapi3TestResp:
      properties:
        amount:
          minimum: 0
          type: integer
        id:
          example: XXX-XXXXX
          type: string
        items:
          items:
            properties:
              count:
                minimum: 0
                type: integer
              name:
                type: string
            type: object
          type: array
        updated_at:
          format: date-time
          type: string
      type: object

Documentation

Overview

Package openapi provides tools and mappings for OpenAPI specs.

Index

Constants

View Source
const (
	InPath     = In("path")
	InQuery    = In("query")
	InHeader   = In("header")
	InCookie   = In("cookie")
	InFormData = In("formData")
	InBody     = In("body")
)

In values enumeration.

Variables

This section is empty.

Functions

func SanitizeMethodPath

func SanitizeMethodPath(method, pathPattern string) (cleanMethod string, cleanPath string, pathParams []string, err error)

SanitizeMethodPath validates method and parses path element names.

func WithContentType added in v0.2.37

func WithContentType(contentType string) func(cu *ContentUnit)

WithContentType is a ContentUnit option.

func WithHTTPStatus added in v0.2.37

func WithHTTPStatus(httpStatus int) func(cu *ContentUnit)

WithHTTPStatus is a ContentUnit option.

func WithOperationCtx

func WithOperationCtx(oc OperationContext, isProcessingResponse bool, in In) func(rc *jsonschema.ReflectContext)

WithOperationCtx is a jsonschema.ReflectContext option.

Types

type ContentOption

type ContentOption func(cu *ContentUnit)

ContentOption configures ContentUnit.

type ContentUnit

type ContentUnit struct {
	Structure   interface{}
	ContentType string
	Format      string

	// HTTPStatus can have values 100-599 for single status, or 1-5 for status families (e.g. 2XX)
	HTTPStatus int

	// IsDefault indicates default response.
	IsDefault bool

	Description string
	// contains filtered or unexported fields
}

ContentUnit defines HTTP content.

func (ContentUnit) FieldMapping

func (c ContentUnit) FieldMapping(in In) map[string]string

FieldMapping returns custom field mapping.

func (*ContentUnit) SetFieldMapping

func (c *ContentUnit) SetFieldMapping(in In, fieldToParamName map[string]string)

SetFieldMapping sets custom field mapping.

type ContentUnitPreparer added in v0.2.37

type ContentUnitPreparer interface {
	SetupContentUnit(cu *ContentUnit)
}

ContentUnitPreparer defines self-contained ContentUnit.

type In

type In string

In defines value location in HTTP content.

type JSONSchemaCallback

type JSONSchemaCallback func(in In, paramName string, schema *jsonschema.SchemaOrBool, required bool) error

JSONSchemaCallback is a user function called by JSONSchemaWalker.

type JSONSchemaWalker

type JSONSchemaWalker interface {
	ResolveJSONSchemaRef(ref string) (s jsonschema.SchemaOrBool, found bool)
	WalkRequestJSONSchemas(method string, cu ContentUnit, cb JSONSchemaCallback, done func(oc OperationContext)) error
	WalkResponseJSONSchemas(cu ContentUnit, cb JSONSchemaCallback, done func(oc OperationContext)) error
}

JSONSchemaWalker can extract JSON schemas (for example, for validation purposes) from a ContentUnit.

type OperationContext

type OperationContext interface {
	OperationInfo
	OperationInfoReader
	OperationState

	Method() string
	PathPattern() string

	Request() []ContentUnit
	Response() []ContentUnit

	AddReqStructure(i interface{}, options ...ContentOption)
	AddRespStructure(o interface{}, options ...ContentOption)

	UnknownParamsAreForbidden(in In) bool
}

OperationContext defines operation and processing state.

func OperationCtx

func OperationCtx(rc *jsonschema.ReflectContext) (OperationContext, bool)

OperationCtx retrieves operation context from reflect context.

type OperationInfo

type OperationInfo interface {
	SetTags(tags ...string)
	SetIsDeprecated(isDeprecated bool)
	SetSummary(summary string)
	SetDescription(description string)
	SetID(operationID string)

	AddSecurity(securityName string, scopes ...string)
}

OperationInfo extends OperationContext with general information.

type OperationInfoReader added in v0.2.46

type OperationInfoReader interface {
	Tags() []string
	IsDeprecated() bool
	Summary() string
	Description() string
	ID() string
}

OperationInfoReader exposes current state of operation context.

type OperationState

type OperationState interface {
	IsProcessingResponse() bool
	ProcessingIn() In

	SetIsProcessingResponse(isProcessingResponse bool)
	SetProcessingIn(in In)
}

OperationState extends OperationContext with processing state information.

type Reflector

type Reflector interface {
	JSONSchemaWalker

	NewOperationContext(method, pathPattern string) (OperationContext, error)
	AddOperation(oc OperationContext) error

	SpecSchema() SpecSchema
	JSONSchemaReflector() *jsonschema.Reflector
}

Reflector defines OpenAPI reflector behavior.

type RequestBodyEnforcer

type RequestBodyEnforcer interface {
	ForceRequestBody()
}

RequestBodyEnforcer enables request body for GET and HEAD methods.

Should be implemented on input structure, function body can be empty. Forcing request body is not recommended and should only be used for backwards compatibility.

type RequestJSONBodyEnforcer

type RequestJSONBodyEnforcer interface {
	ForceJSONRequestBody()
}

RequestJSONBodyEnforcer enables JSON request body for structures with `formData` tags.

Should be implemented on input structure, function body can be empty.

type SpecSchema added in v0.2.36

type SpecSchema interface {
	Title() string
	Description() string
	Version() string

	SetTitle(t string)
	SetDescription(d string)
	SetVersion(v string)

	SetHTTPBasicSecurity(securityName string, description string)
	SetAPIKeySecurity(securityName string, fieldName string, fieldIn In, description string)
	SetHTTPBearerTokenSecurity(securityName string, format string, description string)
}

SpecSchema abstracts OpenAPI schema implementation to generalize multiple revisions.

Directories

Path Synopsis
Package internal keeps reusable internal code.
Package internal keeps reusable internal code.
Package openapi3 provides entities and helpers to manage OpenAPI 3.0.x schema.
Package openapi3 provides entities and helpers to manage OpenAPI 3.0.x schema.
Package openapi31 provides entities and helpers to manage OpenAPI 3.1.x schema.
Package openapi31 provides entities and helpers to manage OpenAPI 3.1.x schema.

Jump to

Keyboard shortcuts

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