Swagger & OpenAPI Specification

table of Contents

OpenAPI Specification

Swagger Specification is an API Specification (API Specification). In 2015, SmartBear Software donated Swagger Specification to Linux Foundation and renamed it as OpenAPI Specification , abbreviated as (OAS). SmartBearSoftware is also a founding member of the OpenAPI Initiative (OAI), which manages the development of OAS in an open and transparent manner.

OpenAPI Specification is essentially a RESTful API API Description Format (description format), allowing users to describe the entire API. The OpenAPI specification can be written in YAML or JSON, including:

  • Available endpoints (eg /users) and operations (eg GET /users, POST /users) of each API.
  • Operation parameters The input and output of each operation.
  • verification method.
  • Contact information, licenses, terms of use and other information.

Usually, we can manually write an OpenAPI Specification as needed or let it be automatically generated from the comments in the source code.

Swagger ecological components

Swagger is a series of ecological components based on the OpenAPI Specification:

  • Swagger Hub : Design and documentation platform based on OpenAPI Specification.
  • Swagger Inspector : Test platform based on OpenAPI Specification.
  • Swagger Editor : Browser-based editor, we can use it to write our OpenAPI specifications.
  • Swagger Codegen : A code generation tool (server or client) based on the OpenAPI Specification.
  • Swagger UI : Present the OpenAPI specification we wrote as an interactive API document.
  • ReDoc : An elegant OpenAPI Specification UI platform.

Write OpenAPI specification files

basic concepts

OpenAPI Root Object (root object)

Insert picture description here

Insert picture description here

OpenAPI data type

Insert picture description here

Define a request API

A request API is mainly composed of Endpoint, Parameters, Body, etc. We need to define them separately.

  • Official example: https://editor.swagger.io/

Define meta information (Metadata)

Insert picture description here

title: 这是标题(必填)。
description: 这里是一段描述。
termsOfService: API 可以测试地址。
contact:
  name: 联系人。
  url: 联系人地址。
  email: 联系人邮箱。
license:
  name: Apache 2.0 授权信息
  url: https://www.apache.org/licenses/LICENSE-2.0.html
version: OpenAPI 版本号(必填)

Define request endpoint

/pets:  # API 请求路径,如果需要 path value 可以使用 /pets/{petId}。
  get:  # get 请求,同理还有 put,post,delete,options 等方法。
    description: 这是一段描述信息。
    responses:  # 响应部分定义。
      '200':  # 响应码。
        description: 又是一段描述 。
        content: # 内容。
          application/json:  # context-type。
            schema:
              type: array  # 类型。
              items:  # array 字段所包含的元素。
                $ref: '#/components/schemas/pet'  # 引用组件,每个元素是一个组件,下文详细说明。

Definition request Parameters

Insert picture description here

  • Add parameters in the Header.
name: token
in: header # 这里是固定值。
description: token to be passed as a header # 描述信息。
required: true # 是否必需的。
schema:
  type: array # 类型。
  items:
    type: integer
    format: int64
  • Add parameters in Path.
name: username
in: path # 这里是固定值。
description: username to fetch
required: true
schema:
  type: string
  • Add parameters in Query.
name: id
in: query # 这里是固定值。
description: ID of the object to fetch
required: false
schema:
  type: array
  items:
    type: string
style: form
explode: true

Define request body

Here use requestBody as the request body.

description: user to add to the system # 描述信息。
content:  # 定义请求体。
  'application/json': # context-type
    schema: # 请求的格式。
      $ref: '#/components/schemas/User' # 组件。
    examples: # 例子。
      user:
        summary: User Example
        externalValue: 'http://foo.bar/examples/user-example.json'

  'application/xml': # context-type
    schema:
      $ref: '#/components/schemas/User'
    examples:
      user:
        summary: User Example in XML
        externalValue: 'http://foo.bar/examples/user-example.xml'

  'text/plain': # context-type
    examples:
      user:
        summary: User example in text plain format
        externalValue: 'http://foo.bar/examples/user-example.txt'

  '*/*':
    examples: # context-type
      user: 
        summary: User example in other format
        externalValue: 'http://foo.bar/examples/user-example.whatever'

Define reusable components

When we use tools like curl to call the API, we usually write Request Body using JSON format classes. In order to make the Request Body have a certain reusability, OpenAPI introduced the concept of Components. In short, it is a reusable schema.

components:
  schemas:
    ErrorModel:
      type: object
      required:
      - message
      - code
      properties:
        message:
          type: string
        code:
          type: integer
          minimum: 100
          maximum: 600
    ExtendedErrorModel:
      allOf:
      - $ref: '#/components/schemas/ErrorModel'
      - type: object
        required:
        - rootCause
        properties:
          rootCause:
            type: string

Example

# OpenAPI的版本,可用版本  3.0.0, 3.0.1, 3.0.2
openapi: 3.0.0
info:
  title: '标题'
  description: '描述'
  version: '此OAS的版本,示例0.1.9'
 
# 提供此 API 的服务器地址列表
servers:
  - url: http://api.example.com/v1
    description: Optional server description, e.g. Main (production) server
  - url: http://staging-api.example.com
    description: Optional server description, e.g. Internal staging server for testing
 
# API 端点列表
paths:
  # 端点 /users
  /users:
    # 端点 /users 的 GET 方法
    get:
      # 描述性信息
      summary: Returns a list of users.
      description: Optional extended description in CommonMark or HTML.
      # 响应规格说明
      responses:
        # 200响应说明
        '200':    # status code
          description: A JSON array of user names
          # 200 响应是 JSON 格式
          content:
            application/json:
              # JSON 的 Schema
              schema: 
                # 数组类型
                type: array
                items: 
                  type: string
    # 端点 /users 的 POST 方法
    post:
      summary: Creates a user.
      # 请求体
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                username:
                  type: string
      responses: 
        '201':
          description: Created
  # 端点 /user/{userId} 的 POST 方法
  # {} 中的是路径变量
  /user/{
    
    userId}:
    get:
      summary: Returns a user by ID.
      # 参数说明
      parameters:
        - name: userId
          # 这是一个路径变量
          in: path
          required: true
          description: The ID of the user to return.
          # Schema 中可以包含字段的验证规则
          schema:
            type: integer
            format: int64
            minimum: 1
      responses:
        '200':
          description: A user object.
          content:
            application/json:
              schema:
                # 对象类型
                type: object
                # 包含属性声明
                properties:
                  id:
                    type: integer
                    format: int64
                    example: 4
                  name:
                    type: string
                    example: Jessica Smith
        # 异常处理
        '400':
          description: The specified user ID is invalid (not a number).
        '404':
          description: A user with the specified ID was not found.
        default:
          description: Unexpected error

Reference documents

https://help.coding.net/docs/management/api/import/openapi.html
https://www.breakyizhan.com/swagger/2806.html

Guess you like

Origin blog.csdn.net/Jmilk/article/details/108498624