OAS 介绍

The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.

An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.

— oas specification

The OpenAPI Specification(OAS)的目标是针对RESTful API,定义标准的、与实现语言无关的接口,同时允许计算机和人都能够理解与发现,无需阅读源码。

概览

OAS的规格包含如下元素

  1. Versions

  2. Format

  3. Document Types

  4. Rich Text Formatting

  5. Relative References in

  6. URLs

  7. Schema

  8. Specification Extensions

  9. Security Filtering

Versions

OAS 的version属性遵循Semantic Versioning 2.0.0规范,采用MAJOR.MINOR.PATCH形式

Format

OpenAPI Specification规定Open API document应该是一个JSON对象,在展现形式上可以是json或者yaml文件格式。

所有属性名称是大小写有别的。

而schema的属性(field)有两种类型:

  • 固定(fixed)

  • 模式(patterned)

后者在包含的对象中必须拥有唯一的名称。

文档结构(Document Structure)

OpenAPI文档可以是单一文档,也可以由作者根据意愿分为多个部分后组成一个文档,通过使用$ref属性引用相关的部分。

所有这些文档必须符合Json Schema的定义

数据类型(Data Types)

基本数据类型基于 JSON Schema Specification Wright Draft 00

Note
integer属性是是没有小数或者指数的JSON number. null 不属于类型 而Model则使用Schema Object定义

基本类型具有可选的修饰符: format

OAS的定义见附件A

多样文本格式(Rich Text Formatting)

在OAS的定义中,description需要支持符合CommonMark语义的markdown格式。

URLs中的相关引用(Relative References in URLs)

相关引用使用$ref,会被当作JSON Reference进行处理

Schema

OpenAPI 文档结构

Table 1. Fix Fields
Field Name Type Required Description

openapi

string

Y

采用semantic version number(OAS 2.0版本此属性为swagger,值只能为2.0),这个属性是指文档采用的OAS版本,和info.version没有关系

info

Info Object

Y

提供API的metadata

servers

[Server Object]

N

An array of Server Objects, which provide connectivity information to a target server.

paths

Paths Object

Y

The available paths and operations for the API.

components

Components Object

N

An element to hold various schemas for the specification.

security

[Security Requirement Object]

N

A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement ({}) can be included in the array.

tags

[Tag Object]

N

A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique.

externalDocs

External Documentation Object

N

Additional external documentation.

Example 1. 完整示例
openapi: "3.0.0"                             (1)
info:                                        (2)
  version: "0.0.1"
  title: "Swagger UI Webpack Setup"
  description: "Demonstrates Swagger UI with Webpack including CSS and OAuth"
servers:                                     (3)
  - url: "https://demo.identityserver.io/api"
    description: "开发环境"
  - url: "https://demo1.identityserver.io/api"
    description: "线上环境"
components:                                  (4)
  securitySchemes:
    # See https://demo.identityserver.io/ for configuration details.
    identity_server_auth:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: "https://demo.identityserver.io/connect/authorize"
          scopes:
            api: "api"
security:                                    (5)
  - identity_server_auth:
    - api
paths:                                       (6)
  /test:                                     (7)
    get:                                     (8)
      summary: "Runs a test request against the Identity Server demo API"
      responses:
        401:
          description: "Unauthorized"
        200:
          description: "OK"
        23283239:
          description: "III
  1. openapi版本

  2. Info Object

  3. Server Objects

  4. Components Object

  5. Security Requirement Objects

  6. Paths Object

  7. Path Templating Matching

  8. Path Item Object

Info Object

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

Table 2. Fix Fields
Field Name Type Required Description

title

string

Y

The title of the API.

description

string

N

A short description of the API. CommonMark syntax MAY be used for rich text representation.

termsOfService

string

N

A URL to the Terms of Service for the API. MUST be in the format of a URL.

contact

Contact Object

N

The contact information for the exposed API.

license

License Object

N

The license information for the exposed API.

version

string

Y

The version of the OpenAPI document(不同于OpenAPI属性)

Example 2. Info Object示例
{
  "title": "Sample Pet Store App",
  "description": "This is a sample server for a pet store.",
  "termsOfService": "http://example.com/terms/",
  "contact": {
    "name": "API Support",
    "url": "http://www.example.com/support",
    "email": "support@example.com"
  },
  "license": {
    "name": "Apache 2.0",
    "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
  },
  "version": "1.0.1"
}
title: Sample Pet Store App
description: This is a sample server for a pet store.
termsOfService: http://example.com/terms/
contact:            (1)
  name: API Support
  url: http://www.example.com/support
  email: support@example.com
license:            (2)
  name: Apache 2.0
  url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.1
  1. Contact Object

  2. License Object

Server Object

An object representing a Server.

Table 3. Fix Fields
Field Name Type Required Description

url

string

Y

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}.

description

string

N

An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation.

variables

Map[string, Server Variable Object]

N

A map between a variable name and its value. The value is used for substitution in the server’s URL template.

Example 3. Server Object Example
{
  "url": "https://development.gigantic-server.com/v1",
  "description": "Development server"
}
url: https://development.gigantic-server.com/v1
description: Development server
Example 4. Multiple Server Object Example
{
  "servers": [
    {
      "url": "https://development.gigantic-server.com/v1",
      "description": "Development server"
    },
    {
      "url": "https://staging.gigantic-server.com/v1",
      "description": "Staging server"
    },
    {
      "url": "https://api.gigantic-server.com/v1",
      "description": "Production server"
    }
  ]
}
servers:
- url: https://development.gigantic-server.com/v1
  description: Development server
- url: https://staging.gigantic-server.com/v1
  description: Staging server
- url: https://api.gigantic-server.com/v1
  description: Production server

Server Variable Object

An object representing a Server Variable for server URL template substitution.

Table 4. Fix Fields
Field Name Type Required Description

enum

[string]

N

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

Y

The default value to use for substitution, which SHALL be sent if an alternate value is not supplied.

description

string

N

An optional description for the server variable.

Example 5. Server Variables Examples
{
  "servers": [
    {
      "url": "https://{username}.gigantic-server.com:{port}/{basePath}",
      "description": "The production API server",
      "variables": {
        "username": {
          "default": "demo",
          "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
        },
        "port": {
          "enum": [
            "8443",
            "443"
          ],
          "default": "8443"
        },
        "basePath": {
          "default": "v2"
        }
      }
    }
  ]
}
servers:
- url: https://{username}.gigantic-server.com:{port}/{basePath}
  description: The production API server
  variables:
    username:
      # note! no enum here means it is an open value
      default: demo
      description: this value is assigned by the service provider, in this example `gigantic-server.com`
    port:
      enum:
        - '8443'
        - '443'
      default: '8443'
    basePath:
      # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`
      default: v2

Paths Object

Example 6. Paths Object 结构如下
paths:
  /path1:                   (1)
    get:                    (2)
      description: xxx      (3)
      summary: xxx          (4)
      tags: []              (5)
      operationId: xxx      (6)
      parameters:           (7)
      requestBody: {}       (8)
      responses: []         (9)
      security: []          (10)
    post:
    put:
  path2:
    get:
    post:
    put:
  1. 接口路径

  2. 接口Http方法

  3. 接口详细说明

  4. 接口简略说明

  5. 接口标签

  6. 接口ID

  7. 请求参数

  8. 请求体

  9. 响应体

  10. 安全需求

Path Item Object

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

Table 5. Fix Fields
Field Name Type Description

$ref

string

Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined.

summary

string

An optional, string summary, intended to apply to all operations in this path.

description

string

An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation.

get

Operation Object

A definition of a GET operation on this path.

put

Operation Object

A definition of a PUT operation on this path.

post

Operation Object

A definition of a POST operation on this path.

delete

Operation Object

A definition of a DELETE operation on this path.

options

Operation Object

A definition of a OPTIONS operation on this path.

head

Operation Object

A definition of a HEAD operation on this path.

patch

Operation Object

A definition of a PATCH operation on this path.

trace

Operation Object

A definition of a TRACE operation on this path.

servers

[Server Object]

An alternative server array to service all operations in this path.

parameters

[Parameter Object | Reference Object]

A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters.

Example 7. Path Item Object Example
{
  "get": {
    "description": "Returns pets based on ID",
    "summary": "Find pets by ID",
    "operationId": "getPetsById",
    "responses": {
      "200": {
        "description": "pet response",
        "content": {
          "*/*": {
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          }
        }
      },
      "default": {
        "description": "error payload",
        "content": {
          "text/html": {
            "schema": {
              "$ref": "#/components/schemas/ErrorModel"
            }
          }
        }
      }
    }
  },
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "description": "ID of pet to use",
      "required": true,
      "schema": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "style": "simple"
    }
  ]
}
get:         (1)
  description: Returns pets based on ID
  summary: Find pets by ID   (2)
  operationId: getPetsById   (3)
  responses:
    '200':                   (4)
      description: pet response
      content:
        '*/*' :              (5)
          schema:
            type: array
            items:
              $ref: '#/components/schemas/Pet'   (6)
    default:                                     (7)
      description: error payload
      content:
        'text/html':
          schema:
            $ref: '#/components/schemas/ErrorModel'
parameters:                    (8)
- name: id
  in: path
  description: ID of pet to use
  required: true
  schema:
    type: array
    items:
      type: string
  style: simple
  1. Http方法

  2. 接口名称

  3. 接口ID

  4. 响应状态码

  5. MediaType

  6. 引用

  7. 默认响应

  8. 参数

External Documentation Object

Allows referencing an external resource for extended documentation.

Table 6. Fix Fields
Field Name Type Required Description

description

string

N

A short description of the target documentation.

url

string

Y

The URL for the target documentation.

Example 8. External Documentation Object Example
{
  "description": "Find more info here",
  "url": "https://example.com"
}
description: Find more info here
url: https://example.com

Components Object

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

Table 7. Fix Fields
Field Name Type Required Description

schemas

Map[string, Schema Object

Reference Object]

N

An object to hold reusable Schema Objects.

responses

Map[string, Response Object

Reference Object]

N

An object to hold reusable Response Objects.

parameters

Map[string, Parameter Object

Reference Object]

N

An object to hold reusable Parameter Objects.

examples

Map[string, Example Object

Reference Object]

N

An object to hold reusable Example Objects.

requestBodies

Map[string, Request Body Object

Reference Object]

N

An object to hold reusable Request Body Objects.

headers

Map[string, Header Object

Reference Object]

N

An object to hold reusable Header Objects.

securitySchemes

Map[string, Security Scheme Object

Reference Object]

N

An object to hold reusable Security Scheme Objects.

links

Map[string, Link Object

Reference Object]

N

An object to hold reusable Link Objects.

callbacks

Map[string, Callback Object

Reference Object]

N

Note
所有的field name必须匹配表达式 ^[a-zA-Z0-9\.\-_]+$
Example 9. Field Name Examples:

User User_1 User_Name user-name my.org.User

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

Components 示例

Example 11. components示例
components:
  #-------------------------------
  # Reusable schemas (data models)
  #-------------------------------
  schemas:
    User:             # Can be referenced as '#/components/schemas/User'
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string

    Error:            # Can be referenced as '#/components/schemas/Error'
      type: object
      properties:
        code:
          type: integer
        message:
          type: string

  #-------------------------------
  # Reusable operation parameters
  #-------------------------------
  parameters:
    offsetParam:      # Can be referenced via '#/components/parameters/offsetParam'
      name: offset
      in: query
      description: Number of items to skip before returning the results.
      required: false
      schema:
        type: integer
        format: int32
        minimum: 0
        default: 0

    limitParam:       # Can be referenced as '#/components/parameters/limitParam'
      name: limit
      in: query
      description: Maximum number of items to return.
      required: false
      schema:
        type: integer
        format: int32
        minimum: 1
        maximum: 100
        default: 20

  #-------------------------------
  # Reusable responses
  #-------------------------------
  responses:
    404NotFound:       # Can be referenced as '#/components/responses/404NotFound'
      description: The specified resource was not found.

    ImageResponse:     # Can be referenced as '#/components/responses/ImageResponse'
      description: An image.
      content:
        image/*:
          schema:
            type: string
            format: binary

    GenericError:      # Can be referenced as '#/components/responses/GenericError'
      description: An error occurred.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
   securitySchemes:
    name:
      type: http
      scheme: bearer
      bearerFormat: JWT
    basic:
      type: http
      scheme: basic
    apiKey:
      type: apiKey
      name: api_key
      in: query

Appendix A: OAS formats

Table 8. 格式
type format comment

integer

int32

signed 32 bits

integer

int64

signed 64 bits (a.k.a long)

number

float

number

double

string

string

byte

base64 encoded characters

string

binary

any sequence of octets

boolean

string

date

As defined by full-date - RFC3339

string

date-time

As defined by date-time - RFC3339

string

password

A hint to UIs to obscure input.