OpenAPI 规范简要说明

Author: ACatSmiling

Since: 2024-12-14

概述

OpenAPI 规范:OpenAPI Specification,简称 OAS,原称 Swagger 规范,是种机器可读的接口描述语言规范,作用是描述、生成、使用和可视化 Web 服务。其前身是 Swagger 框架的一部分,2015年成为独立项目,由 Linux 基金会的开源合作项目 OpenAPI Initiative 监督。目前最新的 OpenAPI 规范版本是 3.1.0,该版本于 2021 年 2 月 15 日发布。

3.1.0 版本官网:https://swagger.io/specification/

3.0.0 版本中文翻译参考:https://openapi.apifox.cn/

在线编辑:https://editor.swagger.io/

OpenAPI 文档支持 JSON 和 YAML 两种格式,推荐将 OpenAPI 文档命名为 openapi.json 或 openapi.yaml。

框架

OpenAPI Object

OpenAPI Object:是 OpenAPI document根文档对象。包含以下字段:

Field Name Type Description
openapi string REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI document uses. The openapi field SHOULD be used by tooling to interpret the OpenAPI document. This is not related to the API info.version string.
info Info Object REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
jsonSchemaDialect string The default value for the $schema keyword within Schema Objects contained within this OAS document. This MUST be in the form of a URI.
servers [Server Object] An array of Server Objects, which provide connectivity information to a target server. If the servers property is not provided, or is an empty array, the default value would be a Server Object with a url value of /.
paths Paths Object The available paths and operations for the API.
webhooks Map[string, Path Item Object | Reference Object] The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the callbacks feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An example is available.
components Components Object An element to hold various schemas for the document.
security [Security Requirement Object] 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] A list of tags used by the document with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique.
externalDocs External Documentation Object Additional external documentation.

脉络

Info Object

Info Object:提供了 OpenAPI 的元数据信息。包含以下字段:

Field Name Type Description
title string REQUIRED. The title of the API.
summary string A short summary of the API.
description string A description of the API. CommonMark syntax MAY be used for rich text representation.
termsOfService string A URL to the Terms of Service for the API. This MUST be in the form of a URL.
contact Contact Object The contact information for the exposed API.
license License Object The license information for the exposed API.
version string REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version).

示例:

  • json 格式:

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

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

Server Object

Server Object:表示一个服务器的对象。包含以下字段:

Field Name Type Description
url string 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}.
description string 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] A map between a variable name and its value. The value is used for substitution in the server's URL template.

示例:

  • json 格式:

    {
    "url": "https://development.gigantic-server.com/v1",
    "description": "Development server"
    }
  • yaml 格式:

    url: https://development.gigantic-server.com/v1
    description: Development server

以下示例,表示的是有多个服务器时应该如何描述,比如 OpenAPI 对象的 servers

  • json 格式:

    {
    "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"
    }
    ]
    }
  • yaml 格式:

    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

以下示例,展示了如何使用变量配置服务器

  • json 格式:

    {
    "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"
    }
    }
    }
    ]
    }
  • yaml 格式:

    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

Paths Object:定义各个端点及其操作的相对路径。此处指定的路径会和 Server Object 内指定的 URL 地址组成完整的URL地址,路径可以为空,这依赖于 Access Control List (ACL) constraints 的设置。包含以下字段:

Field Pattern Type Description
/ Path Item Object A relative path to an individual endpoint. The field name MUST begin with a forward slash (/). The path is appended (no relative URL resolution) to the expanded URL from the Server Object's url field in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use.

示例:

  • json 格式:

    {
    "/pets": {
    "get": {
    "description": "Returns all pets from the system that the user has access to",
    "responses": {
    "200": {
    "description": "A list of pets.",
    "content": {
    "application/json": {
    "schema": {
    "type": "array",
    "items": {
    "$ref": "#/components/schemas/pet"
    }
    }
    }
    }
    }
    }
    }
    }
    }
  • yaml 格式:

    /pets:
    get:
    description: Returns all pets from the system that the user has access to
    responses:
    '200':
    description: A list of pets.
    content:
    application/json:
    schema:
    type: array
    items:
    $ref: '#/components/schemas/pet'

Path Templating Matching

假设有以下路径,明确定义的路径 "/pets/mine" 会被优先匹配:

/pets/{petId}
/pets/mine

以下路径被认为是等价且无效的:

/pets/{petId}
/pets/{name}

以下路径会产生歧义:

/{entity}/me
/books/{id}

Path Item Object

Path Item Object:描述对一个路径可执行的有效操作。依赖于 ACL constraints 的设置,一个 Path Item 可能是一个空对象,文档的读者仍然可以看到这个路径,但是他们无法了解到对这个路径可用的任何操作和参数。包含以下字段:

Field Name Type Description
$ref string Allows for a referenced definition of this path item. The value MUST be in the form of a URI, and the referenced structure MUST be in the form 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. See the rules for resolving Relative References. Note: The behavior of $ref with adjacent properties is likely to change in future versions of this specification to bring it into closer alignment with the behavior of the Reference Object.
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 servers array to service all operations in this path. If a servers array is specified at the OpenAPI Object level, it will be overridden by this value.
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. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's components.parameters.

示例:

  • json 格式:

    {
    "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"
    }
    ]
    }
  • yaml 格式:

    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

Components Object

Components Object包含 OpenAPI 规范固定的各种可重用组件,当没有被其他对象引用时,在这里定义定义的组件不会产生任何效果。包含以下字段:

Field Name Type Description
schemas Map[string, Schema Object] An object to hold reusable Schema Objects.
responses Map[string, Response Object | Reference Object] An object to hold reusable Response Objects.
parameters Map[string, Parameter Object | Reference Object] An object to hold reusable Parameter Objects.
examples Map[string, Example Object | Reference Object] An object to hold reusable Example Objects.
requestBodies Map[string, Request Body Object | Reference Object] An object to hold reusable Request Body Objects.
headers Map[string, Header Object | Reference Object] An object to hold reusable Header Objects.
securitySchemes Map[string, Security Scheme Object | Reference Object] An object to hold reusable Security Scheme Objects.
links Map[string, Link Object | Reference Object] An object to hold reusable Link Objects.
callbacks Map[string, Callback Object | Reference Object] An object to hold reusable Callback Objects.
pathItems Map[string, Path Item Object | Reference Object] An object to hold reusable Path Item Object.
  • 这个对象可能会被 Specification Extensions 扩展。

  • 上面定义的所有字段的 value 都是对象,对象包含的 key 的命名必须满足正则表达式: ^[a-zA-Z0-9\.\-_]+$。示例如下:

    User
    User_1
    User_Name
    user-name
    my.org.User

示例:

  • json 格式:

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

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

引用示例:

paths:
/pet:
post:
tags:
- pet
summary: Add a new pet to the store
description: Add a new pet to the store
operationId: addPet
requestBody:
description: Create a new pet in the store
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/Pet'
required: true
responses:
'200':
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/xml:
schema:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid input
'422':
description: Validation exception
security:
- petstore_auth:
- write:pets
- read:pets
components:
schemas:
Pet:
required:
- name
- photoUrls
type: object
properties:
id:
type: integer
format: int64
example: 10
name:
type: string
example: doggie
category:
$ref: '#/components/schemas/Category'
photoUrls:
type: array
xml:
wrapped: true
items:
type: string
xml:
name: photoUrl
tags:
type: array
xml:
wrapped: true
items:
$ref: '#/components/schemas/Tag'
status:
type: string
description: pet status in the store
enum:
- available
- pending
- sold
xml:
name: pet

Security Requirement Object

略,详见官网

Tag Object

Tag Object:为 Operation Object 使用的单个标记添加元数据。Operation Object 实例中定义的每个标记不一定必须有一个 Tag Object。包含以下字段:

Field Name Type Description
name string REQUIRED. The name of the tag.
description string A description for the tag. CommonMark syntax MAY be used for rich text representation.
externalDocs External Documentation Object Additional external documentation for this tag.

示例:

  • json 格式:

    {
    "name": "pet",
    "description": "Pets operations"
    }
  • yaml 格式:

    name: pet
    description: Pets operations

External Documentation Object

External Documentation Object:允许引用外部资源来扩展文档。包含以下字段:

Field Name Type Description
description string A description of the target documentation. CommonMark syntax MAY be used for rich text representation.
url string REQUIRED. The URI for the target documentation. This MUST be in the form of a URI.

示例:

  • json 格式:

    {
    "description": "Find more info here",
    "url": "https://example.com"
    }
  • yaml 格式:

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

组成

Contact Object

Contact Object:OpenAPI 的联系人信息。包含以下字段:

Field Name Type Description
name string The identifying name of the contact person/organization.
url string The URL pointing to the contact information. This MUST be in the form of a URL.
email string The email address of the contact person/organization. This MUST be in the form of an email address.

示例:

  • json 格式:

    {
    "name": "API Support",
    "url": "https://www.example.com/support",
    "email": "support@example.com"
    }
  • yaml 格式:

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

License Object

License Object:OpenAPI 的许可证信息。包含以下字段:

Field Name Type Description
name string REQUIRED. The license name used for the API.
identifier string An SPDX license expression for the API. The identifier field is mutually exclusive of the url field.
url string A URL to the license used for the API. This MUST be in the form of a URL. The url field is mutually exclusive of the identifier field.

示例:

  • json 格式:

    {
    "name": "Apache 2.0",
    "identifier": "Apache-2.0"
    }
  • yaml 格式:

    name: Apache 2.0
    identifier: Apache-2.0

Server Variable Object

Server Variable Object:代表服务器变量的对象,用于服务器 URL 模板替换。包含以下字段:

Field Name Type Description
enum [string] An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty.
default string 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 MUST exist in the enum's values.
description string An optional description for the server variable. CommonMark syntax MAY be used for rich text representation.

Operation Object

Operation Object:描述对路径的某个操作。包含以下字段:

Field Name Type Description
tags [string] A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.
summary string A short summary of what the operation does.
description string A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation.
externalDocs External Documentation Object Additional external documentation for this operation.
operationId string Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions.
parameters [Parameter Object | Reference Object] A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's components.parameters.
requestBody Request Body Object | Reference Object The request body applicable for this operation. The requestBody is fully supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), requestBody is permitted but does not have well-defined semantics and SHOULD be avoided if possible.
responses Responses Object The list of possible responses as they are returned from executing this operation.
callbacks Map[string, Callback Object | Reference Object] A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses.
deprecated boolean Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is false.
security [Security Requirement Object] A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement ({}) can be included in the array. This definition overrides any declared top-level security. To remove a top-level security declaration, an empty array can be used.
servers [Server Object] An alternative servers array to service this operation. If a servers array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value.

示例:

  • json 格式:

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

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

Parameter Object

Parameter Object:描述单个操作参数。通过namelocation 的组合,唯一定义了一个 parameter。

有关百分比编码问题的详细研究,包括与 application/x-www-form-urlencoded 查询字符串格式的交互,请参见 Appendix E

Parameter Locations

in字段指定了四个可能的参数位置:

  • path:与 Path Templating 一起使用时,参数值实际上是操作 URL 的一部分。 这不包括 API 的主机或基本路径。 例如,在 "/items/{itemId}" 中,path 参数对应的是 itemId。
  • query参数值会追加到 URL 中。例如,在 "/items?id=####" 中,query 参数对应的是 id。
  • header:header 参数会作为请求的自定义标头。注意,RFC7230 规定在,header 参数不区分大小写。
  • cookie:用于向 API 传递特定的 cookie 值

Fixed Fields

parameter 参数的序列化规则有两种指定方式。Parameter Objects 必须包括content字段或schema字段,但不能同时包括,有关将各种类型的值转换为字符串的讨论,请参见 Appendix B

Common Fixed Fields

包含以下字段,这些字段可用于contentschema

Field Name Type Description
name string REQUIRED. The name of the parameter. Parameter names are case sensitive.If in is "path", the name field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information.If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored.For all other cases, the name corresponds to the parameter name used by the in field.
in string REQUIRED. The location of the parameter. Possible values are "query", "header", "path" or "cookie".
description string A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
required boolean Determines whether this parameter is mandatory. If the parameter location is "path", this field is REQUIRED and its value MUST be true. Otherwise, the field MAY be included and its default value is false.
deprecated boolean Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is false.
allowEmptyValue boolean If true, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is false. If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for query parameters. Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision.
  • 这个对象可能会被 Specification Extensions 扩展。
  • 注意,如果 in 是 header,Cookie 作为 name 并没有被禁止,但这样定义 cookie 参数的效果是未定义的,请使用 in: "cookie" 代替。
Fixed Fields for use with schema

对于较简单的情况,schemastyle 可以描述 parameter 参数的结构和语法。当 example 或 examples 与 schema 字段一起提供时,example 应与指定的模式相匹配,并遵循规定的 parameter 参数序列化策略。example 字段和 examples 字段是互斥的,如果其中任何一个字段出现,都应覆盖 schema 中的任何 example。

包含以下字段:

Field Name Type Description
style string Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of in): for "query" - "form"; for "path" - "simple"; for "header" - "simple"; for "cookie" - "form".
explode boolean 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. For other types of parameters this field has no effect. When style is "form", the default value is true. For all other styles, the default value is false. Note that despite false being the default for deepObject, the combination of false with deepObject is undefined.
allowReserved boolean When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including % outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string ([, ], #), or have a special meaning in application/x-www-form-urlencoded (-, &, +); see Appendices C and E for details. This field only applies to parameters with an in value of query. The default value is false.
schema Schema Object The schema defining the type used for the parameter.
example Any Example of the parameter's potential value; see Working With Examples.
examples Map[ string, Example Object | Reference Object] Examples of the parameter's potentia
Fixed Fields for use with content

对于更复杂的情况,content 字段可以定义 parameter 参数的 media type 以及 schema。在 in: "header" 和 in: "cookie" 两种模式下,content 推荐使用 text/plain,但 schema 字段不适用。

包含以下字段:

Field Name Type Description
content Map[string, Media Type Object] A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry.

Style Values

为了支持简单参数序列化的常用方法,定义了一组 style 值:

style type in Comments
matrix primitive, array, object path Path-style parameters defined by RFC6570
label primitive, array, object path Label style parameters defined by RFC6570
simple primitive, array, object path, header Simple style parameters defined by RFC6570. This option replaces collectionFormat with a csv value from OpenAPI 2.0.
form primitive, array, object query, cookie Form style parameters defined by RFC6570. This option replaces collectionFormat with a csv (when explode is false) or multi (when explode is true) value from OpenAPI 2.0.
spaceDelimited array, object query Space separated array values or object properties and values. This option replaces collectionFormat equal to ssv from OpenAPI 2.0.
pipeDelimited array, object query Pipe separated array values or object properties and values. This option replaces collectionFormat equal to pipes from OpenAPI 2.0.
deepObject object query Allows objects with scalar properties to be represented using form parameters. The representation of array or object properties is not defined.

示例,假设名为 color 的参数具有以下值之一:

string -> "blue"
array -> ["blue", "black", "brown"]
object -> { "R": 100, "G": 200, "B": 150 }

下表列出了每个值的不同序列化示例,与 example 或 examples 关键字一样。

略,详见官网

Examples

header 参数,包含一个 64 位整数数组:

  • json 格式:

    {
    "name": "token",
    "in": "header",
    "description": "token to be passed as a header",
    "required": true,
    "schema": {
    "type": "array",
    "items": {
    "type": "integer",
    "format": "int64"
    }
    },
    "style": "simple"
    }
  • yaml 格式:

    name: token
    in: header
    description: token to be passed as a header
    required: true
    schema:
    type: array
    items:
    type: integer
    format: int64
    style: simple

path 参数,使用 string 值:

  • json 格式:

    {
    "name": "username",
    "in": "path",
    "description": "username to fetch",
    "required": true,
    "schema": {
    "type": "string"
    }
    }
  • yaml 格式:

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

可选的 query 参数,包含一个 string 值,通过重复 query 参数可获得多个值:

  • json 格式:

    {
    "name": "id",
    "in": "query",
    "description": "ID of the object to fetch",
    "required": false,
    "schema": {
    "type": "array",
    "items": {
    "type": "string"
    }
    },
    "style": "form",
    "explode": true
    }
  • yaml 格式:

    name: id
    in: query
    description: ID of the object to fetch
    required: false
    schema:
    type: array
    items:
    type: string
    style: form
    explode: true

自由格式的 query 参数,允许使用未定义的特定类型参数:

  • json 格式:

    {
    "in": "query",
    "name": "freeForm",
    "schema": {
    "type": "object",
    "additionalProperties": {
    "type": "integer"
    }
    },
    "style": "form"
    }
  • yaml 格式:

    in: query
    name: freeForm
    schema:
    type: object
    additionalProperties:
    type: integer
    style: form

使用 content 字段定义序列化的复杂参数(上面的示例,都是使用的 schema 字段定义序列化的参数):

  • json 格式:

    {
    "in": "query",
    "name": "coordinates",
    "content": {
    "application/json": {
    "schema": {
    "type": "object",
    "required": ["lat", "long"],
    "properties": {
    "lat": {
    "type": "number"
    },
    "long": {
    "type": "number"
    }
    }
    }
    }
    }
    }
  • yaml 格式:

    in: query
    name: coordinates
    content:
    application/json:
    schema:
    type: object
    required:
    - lat
    - long
    properties:
    lat:
    type: number
    long:
    type: number

Header Object

Header Object:除了以下改动之外,与 Parameter Object 一致。

  1. name 不能被指定,它在相应的 headers 映射中被指定。
  2. in 不能被指定,它隐含在 header 中。
  3. 所有被 location 影响的特性必须适合 header 中的一个 location,(比如 style)。这意味着不能使用 allowEmptyValue 和 allowReserved,如果使用,style 必须限制为 "simple"。

Fixed Fields

Common Fixed Fields

包含以下字段,这些字段可用于contentschema

Field Name Type Description
description string A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
required boolean Determines whether this header is mandatory. The default value is false.
deprecated boolean Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is false.
Fixed Fields for use with schema

包含以下字段:

Field Name Type Description
style string Describes how the header value will be serialized. The default (and only legal value for headers) is "simple".
explode boolean When this is true, header values of type array or object generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is false.
schema Schema Object | Reference Object The schema defining the type used for the header.
example Any Example of the header's potential value; see Working With Examples.
examples Map[ string, Example Object | Reference Object] Examples of the header's potential value; see Working With Examples.
Fixed Fields for use with content

包含以下字段:

Field Name Type Description
content Map[string, Media Type Object] A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry.

Examples

一个类型为 integer 的简单 header:

  • json 格式:

    {
    "description": "The number of allowed requests in the current period",
    "schema": {
    "type": "integer"
    }
    }
  • yaml 格式:

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

Request Body Object

Request Body Object:定义请求体。包含以下字段:

Field Name Type Description
description string A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
content Map[string, Media Type Object] 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 boolean Determines if the request body is required in the request. Defaults to false.

示例:

  • json 格式:

    {
    "description": "user to add to the system",
    "content": {
    "application/json": {
    "schema": {
    "$ref": "#/components/schemas/User"
    },
    "examples": {
    "user": {
    "summary": "User Example",
    "externalValue": "https://foo.bar/examples/user-example.json"
    }
    }
    },
    "application/xml": {
    "schema": {
    "$ref": "#/components/schemas/User"
    },
    "examples": {
    "user": {
    "summary": "User example in XML",
    "externalValue": "https://foo.bar/examples/user-example.xml"
    }
    }
    },
    "text/plain": {
    "examples": {
    "user": {
    "summary": "User example in Plain text",
    "externalValue": "https://foo.bar/examples/user-example.txt"
    }
    }
    },
    "*/*": {
    "examples": {
    "user": {
    "summary": "User example in other format",
    "externalValue": "https://foo.bar/examples/user-example.whatever"
    }
    }
    }
    }
    }
  • yaml 格式:

    description: user to add to the system
    content:
    application/json:
    schema:
    $ref: '#/components/schemas/User'
    examples:
    user:
    summary: User example
    externalValue: https://foo.bar/examples/user-example.json
    application/xml:
    schema:
    $ref: '#/components/schemas/User'
    examples:
    user:
    summary: User example in XML
    externalValue: https://foo.bar/examples/user-example.xml
    text/plain:
    examples:
    user:
    summary: User example in plain text
    externalValue: https://foo.bar/examples/user-example.txt
    '*/*':
    examples:
    user:
    summary: User example in other format
    externalValue: https://foo.bar/examples/user-example.whatever

Response Object

Response Object:描述单个 API 操作的响应,包括设计时间、基于响应操作的静态 links。包含以下字段:

Field Name Type Description
description string REQUIRED. A description of the response. CommonMark syntax MAY be used for rich text representation.
headers Map[string, Header Object | Reference Object] Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name "Content-Type", it SHALL be ignored.
content Map[string, Media Type Object] A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. "text/plain" overrides "text/*"
links Map[string, Link Object | Reference Object] A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects.

示例,一个包含复杂类型的数组格式的响应:

  • json 格式:

    {
    "description": "A complex object array response",
    "content": {
    "application/json": {
    "schema": {
    "type": "array",
    "items": {
    "$ref": "#/components/schemas/VeryComplexType"
    }
    }
    }
    }
    }
  • yaml 格式:

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

字符串类型的响应:

  • json 格式:

    {
    "description": "A simple string response",
    "content": {
    "text/plain": {
    "schema": {
    "type": "string"
    }
    }
    }
    }
  • yaml 格式:

    description: A simple string response
    content:
    text/plain:
    schema:
    type: string

带 HTTP 头的普通文本类型的响应:

  • json 格式:

    {
    "description": "A simple string response",
    "content": {
    "text/plain": {
    "schema": {
    "type": "string"
    },
    "example": "whoa!"
    }
    },
    "headers": {
    "X-Rate-Limit-Limit": {
    "description": "The number of allowed requests in the current period",
    "schema": {
    "type": "integer"
    }
    },
    "X-Rate-Limit-Remaining": {
    "description": "The number of remaining requests in the current period",
    "schema": {
    "type": "integer"
    }
    },
    "X-Rate-Limit-Reset": {
    "description": "The number of seconds left in the current period",
    "schema": {
    "type": "integer"
    }
    }
    }
    }
  • yaml 格式:

    description: A simple string response
    content:
    text/plain:
    schema:
    type: string
    example: 'whoa!'
    headers:
    X-Rate-Limit-Limit:
    description: The number of allowed requests in the current period
    schema:
    type: integer
    X-Rate-Limit-Remaining:
    description: The number of remaining requests in the current period
    schema:
    type: integer
    X-Rate-Limit-Reset:
    description: The number of seconds left in the current period
    schema:
    type: integer

没有返回值的响应:

  • json 格式:

    {
    "description": "object created"
    }
  • yaml 格式:

    description: object created

Example Object

略,详见官网

Security Scheme Object

略,详见官网

略,详见官网

Callback Object

略,详见官网

通用

Reference Object

略,详见官网

Schema Object

Schema Object:用于定义输入和输出的数据类型,这些类型可以是对象,也可以是原始值和数组。这个对象是 JSON Schema Specification Draft 2020-12 扩展后的子集。

有关属性的更多信息,查看 JSON Schema CoreJSON Schema Validation。除非另有说明,否则属性定义均遵循 JSON Schema 的定义,不添加任何其他语义。

posted @   ACatSmiling  阅读(429)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示