Swagger YAML:学习 Swagger 编写 API 文档的 YAML 示例(中文版)

本文将介绍如何使用 Swagger 编写 API 文档的 YAML 文件,并提供中文示例以帮助读者更好地理解。帮助你了解如何使用 Swagger 工具快速、简便地编写和维护 API 文档。

用 Apifox,节省研发团队的每一分钟

Swagger YAML:学习 Swagger 编写 API 文档的 YAML 示例(中文版)

免费使用 Apifox

相关推荐

最新文章

API

一体化协作平台

API 设计

API 文档

API 调试

自动化测试

API Mock

API Hub

立即体验 Apifox
目录

实话说,Swagger Spec 提供了一套比较容易理解的 API 约定, 利用 Git 工具可以很快的就看到变更。我将再本文中提供一个中文示例,这样大家就能快速地上车。

Swagger 2.0 中文 Yaml 示例

以下是一个swagger 2.0 的 yaml 示例,你可以基于该示例来快速学习 swagger 2.0 文档编写。

#必要字段!Swagger规范版本,必须填2.0,否则该YAML将不能用于Swagger其他组件
swagger: '2.0'
#必要字段!描述API接口信息的元数据
info:
  #接口标题
  title: swagger说明文档 
  #接口文档的描述
  description: 学习Swagger
  #版本号
  version: 1.0.0
#Swagger会提供测试用例,host指定测试时的主机名,如果没有指定就是当前主机,可以指定端口.
host: 127.0.0.1
#定义的api的前缀,必须已/开头,测试用例的主机则为:host+bashPath
basePath: /api
#指定调用接口的协议,必须是:"http", "https", "ws", "wss".默认是http.-表示是个数组元素,即schemes接受一个数组参数
schemes:
  - http
  - https
#对应与http协议头request的Accept,调用者可接受类型,默认是*/*,定义的类型必须是http协议定义的 Mime Types,RestfulAPI一般定义成application/json
#这两个是对所有接口的全局设置,在细化的接口中是还可以对应这两个属性来覆盖全局属性
produces:
  - application/json
#必要字段!定义可有可操作的API
paths:
  /users:
   #必要字段!定义HTTP操作方法,必须是http协议定义的方法
    get:
      #接口概要
      summary: 查询所有用户信息
      #接口描述
      description: 查询出所有用户的所有信息,用户名,别名
      #标签,方便快速过滤出User相关的接口
      tags:
        - User
      #返回值描述,必要自动
      responses:
        #返回的http状态码
        200:
          description: 所有用户信息或者用户的集合信息
          #描述返回值
          schema:
            #返回值格式,可选的有array,integer,string,boolean
            type: array
            #针对array,每个条目的格式,type定义为array.必要填写items
            items:
              #引用在definitions下定义的Users
              $ref: '#/definitions/User'
        #执行出错的处理
        default:
          description: 操作异常,执行失败.返回信息描述错误详情
          schema:
            #值类型
            type: object
            #定义属性
            properties:
            #属性名
              message:
                #类型
                type: string
    #即对于同一个url定义两个不同的方法,表示两个接口
    post:
      description: 注册一个用户
      #请求参数
      parameters:
          #参数key
        - name: username
          #传递方法,formData表示表单传输,还有query表示url拼接传输,path表示作为url的一部分
          #body表示http头承载参数(body只能有一个,有body不能在有其他的)
          in: formData
          #参数描述
          description: 用户名,不能使用已经被注册过的
          #参数是否必要,默认false
          required: true
          #参数类型,可选的包括array,integer,boolean,string.使用array必须使用items
          type: string
        - name: password
          in: formData
          description: 用户登陆密码,加密传输,加密存储
          required: true
          type: string
        - name: alias
          in: formData
          type: string
          description: 用户别名
          #非必要字段
          required: false
      responses:
        #返回的http状态码
        200:
          description: 通过返回值来标示执行结果 返回true表示执行成功
          schema:
             #值类型
              type: object
              #定义属性
              properties:
              #属性名
                status:
                  #类型
                  type: boolean
                  #描述
                  description: 是否成功
        #执行出错的处理
        default:
          description: 操作异常,执行失败.返回信息描述错误详情
          schema:
            #值类型
            type: object
            #定义属性
            properties:
            #属性名
              message:
                #类型
                type: string
  /users/{id}:
    #{id}表示id为请求参数,例如/users/1,/users/2都是对该API的请求,此时id即为1和2
    get:
      summary: 根据用户名id查询该用户的所有信息
      description: 查询出某个用户的所有信息,用户名,别名等
      tags:
        - User
      parameters:
        #上面接口中定义了{id},则参数列表中必须包含参数id,并且请求类型为path
        - name: id
          in: path
          description: 要查询的用户的用户名,它是唯一标识
          required: true
          type: string
      responses:
        200:
          description: 所有用户信息或者用户的集合信息
          schema:
              $ref: '#/definitions/User'
        default:
          description: 操作异常,执行失败.返回信息描述错误详情
          schema:
              #值类型
              type: object
              #定义属性
              properties:
              #属性名
                message:
                  #类型
                  type: string
    #http定义的delete方法,删除一个资源
    delete:
      summary: 删除用户
      description: 删除某个用户的信息,被删除的用户将无法登陆
      parameters:
        - name: id
          in: path
          type: string
          required: true
          description: 用户的唯一标示符
      tags:
        - User
      responses:
        200:
          description: 通过返回值来标示执行结果 返回true表示执行成功
          schema:
             #值类型
              type: object
              #定义属性
              properties:
              #属性名
                status:
                  #类型
                  type: boolean
                  #描述
                  description: 是否成功
        default:
          description: 操作异常,执行失败.返回信息描述错误详情
          schema:
              #值类型
              type: object
              #定义属性
              properties:
              #属性名
                message:
                  #类型
                  type: string
                  #描述错误信息
    #http定义的patch方法,表示修改一个资源
    patch:
      summary: 用户信息修改
      description: 修改用户信息(用户名别名)
      parameters: 
        - name: id
          in: path
          description: 用户名,要修改的数据的唯一标识符
          required: true
          type: string
        - name: alias
          in: formData
          description: 新的用户别名
          required: true
          type: string
      tags:
        - User
      responses:
        200:
          description: 通过返回值来标示执行结果 返回true表示执行成功
          schema:
            #值类型
              type: object
              #定义属性
              properties:
              #属性名
                status:
                  #类型
                  type: boolean
                  #描述
                  description: 是否成功
        default:
          description: 操作异常,执行失败.返回信息描述错误详情
          schema:
              #值类型
              type: object
              #定义属性
              properties:
              #属性名
                message:
                  #类型
                  type: string
                  #描述错误信息
definitions:
  User:
    #值类型
    type: object
    #定义属性
    properties:
    #属性名
      id:
        #类型
        type: string
        #描述
        description: 用户的唯一id
      username:
        type: string
        description: 用户名
      alias:
        type: string
        description: 别名

OpenAPI 3.0 中文 Yaml 示例

以下是一个 OpenAPI 3.0 的 yaml 示例,推荐你结合 OpenAPI 3.0 规范中文版 来一起学习。

openapi: "3.0.2"
info:
  title: "OpenWeatherMap API"
  description: "Get the current weather, daily forecast for 16 days, and a three-hour-interval forecast for 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API. <br/><br/> **Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results."
  version: "2.5"
  termsOfService: "https://openweathermap.org/terms"
  contact:
    name: "OpenWeatherMap API"
    url: "https://openweathermap.org/api"
    email: "some_email@gmail.com"
  license:
    name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)"
    url: "https://openweathermap.org/price"

servers:
- url: "https://api.openweathermap.org/data/2.5"

paths:
  /weather:
    get:
      tags:
      - Current Weather Data
      summary: "Call current weather data for one location"
      description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations."
      operationId: CurrentWeatherData
      parameters:
        - $ref: '#/components/parameters/q'
        - $ref: '#/components/parameters/id'
        - $ref: '#/components/parameters/lat'
        - $ref: '#/components/parameters/lon'
        - $ref: '#/components/parameters/zip'
        - $ref: '#/components/parameters/units'
        - $ref: '#/components/parameters/lang'
        - $ref: '#/components/parameters/mode'

      responses:
        "200":
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/200'
        "404":
          description: Not found response
          content:
            text/plain:
              schema:
                title: Weather not found
                type: string
                example: Not found
security:
- app_id: []

tags:
  - name: Current Weather Data
    description: "Get current weather details"

externalDocs:
  description: API Documentation
  url: https://openweathermap.org/api

components:

  parameters:
    q:
      name: q
      in: query
      description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by a comma; use ISO 3166 country codes."
      schema:
        type: string
    id:
      name: id
      in: query
      description: "**City ID**. *Example: `2172797`*. You can call by city ID. The API responds with the exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in this parameter &mdash; just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs, it's treated as 3 API calls.*"
      schema:
        type: string

    lat:
      name: lat
      in: query
      description: "**Latitude**. *Example: 35*. The latitude coordinate of the location of your interest. Must use with `lon`."
      schema:
        type: string

    lon:
      name: lon
      in: query
      description: "**Longitude**. *Example: 139*. Longitude coordinate of the location of your interest. Must use with `lat`."
      schema:
        type: string

    zip:
      name: zip
      in: query
      description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note that if the country is not specified, the search uses USA as a default."
      schema:
        type: string

    units:
      name: units
      in: query
      description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use the `units` parameter, the format is `standard` by default.'
      schema:
        type: string
        enum: [standard, metric, imperial]
        default: "imperial"

    lang:
      name: lang
      in: query
      description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.'
      schema:
        type: string
        enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw]
        default: "en"

    mode:
      name: mode
      in: query
      description: "**Mode**. *Example: html*. Determines the format of the response. Possible values are `json`, `xml`, and `html`. If the mode parameter is empty, the format is `json` by default."
      schema:
        type: string
        enum: [json, xml, html]
        default: "json"

  schemas:
    "200":
      title: Successful response
      type: object
      properties:
        coord:
          $ref: '#/components/schemas/Coord'
        weather:
          type: array
          items:
            $ref: '#/components/schemas/Weather'
          description: (more info Weather condition codes)
        base:
          type: string
          description: Internal parameter
          example: cmc stations
        main:
          $ref: '#/components/schemas/Main'
        visibility:
          type: integer
          description: Visibility, meter
          example: 16093
        wind:
          $ref: '#/components/schemas/Wind'
        clouds:
          $ref: '#/components/schemas/Clouds'
        rain:
          $ref: '#/components/schemas/Rain'
        snow:
          $ref: '#/components/schemas/Snow'
        dt:
          type: integer
          description: Time of data calculation, unix, UTC
          format: int32
          example: 1435658272
        sys:
          $ref: '#/components/schemas/Sys'
        id:
          type: integer
          description: City ID
          format: int32
          example: 2172797
        name:
          type: string
          example: Cairns
        cod:
          type: integer
          description: Internal parameter
          format: int32
          example: 200
    Coord:
      title: Coord
      type: object
      properties:
        lon:
          type: number
          description: City geo location, longitude
          example: 145.77000000000001
        lat:
          type: number
          description: City geo location, latitude
          example: -16.920000000000002
    Weather:
      title: Weather
      type: object
      properties:
        id:
          type: integer
          description: Weather condition id
          format: int32
          example: 803
        main:
          type: string
          description: Group of weather parameters (Rain, Snow, Extreme etc.)
          example: Clouds
        description:
          type: string
          description: Weather condition within the group
          example: broken clouds
        icon:
          type: string
          description: Weather icon id
          example: 04n
    Main:
      title: Main
      type: object
      properties:
        temp:
          type: number
          description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.'
          example: 293.25
        pressure:
          type: integer
          description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa
          format: int32
          example: 1019
        humidity:
          type: integer
          description: Humidity, %
          format: int32
          example: 83
        temp_min:
          type: number
          description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.'
          example: 289.81999999999999
        temp_max:
          type: number
          description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.'
          example: 295.37
        sea_level:
          type: number
          description: Atmospheric pressure on the sea level, hPa
          example: 984
        grnd_level:
          type: number
          description: Atmospheric pressure on the ground level, hPa
          example: 990
    Wind:
      title: Wind
      type: object
      properties:
        speed:
          type: number
          description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.'
          example: 5.0999999999999996
        deg:
          type: integer
          description: Wind direction, degrees (meteorological)
          format: int32
          example: 150
    Clouds:
      title: Clouds
      type: object
      properties:
        all:
          type: integer
          description: Cloudiness, %
          format: int32
          example: 75
    Rain:
      title: Rain
      type: object
      properties:
        3h:
          type: integer
          description: Rain volume for the last 3 hours
          format: int32
          example: 3
    Snow:
      title: Snow
      type: object
      properties:
        3h:
          type: number
          description: Snow volume for the last 3 hours
          example: 6
    Sys:
      title: Sys
      type: object
      properties:
        type:
          type: integer
          description: Internal parameter
          format: int32
          example: 1
        id:
          type: integer
          description: Internal parameter
          format: int32
          example: 8166
        message:
          type: number
          description: Internal parameter
          example: 0.0166
        country:
          type: string
          description: Country code (GB, JP etc.)
          example: AU
        sunrise:
          type: integer
          description: Sunrise time, unix, UTC
          format: int32
          example: 1435610796
        sunset:
          type: integer
          description: Sunset time, unix, UTC
          format: int32
          example: 1435650870

  securitySchemes:
    app_id:
      type: apiKey
      description: "API key to authorize requests. (If you don't have an API key, get one at https://openweathermap.org/. See https://idratherbewriting.com/learnapidoc/docapis_get_auth_keys.html for details.)"
      name: appid
      in: query

以上就是 Swagger 2.0和 OpenAPI 3.0 的示例 Yaml。

设计 API 更快捷的方式

用过了 Swagger Editor 会发现,编辑调整 Swagger 必须得非常小心,特别是涉及复杂的 Schema。这里我强烈推荐 Apifox , 它是 API一体化平台,功能囊括了 API 设计, 调试,自动化测试和 API 文档协作, 它比较适合现代的开发方式,无论你是设计优先还是代码优先。你可以在 Apifox 中一边设计并调试 API ,一遍学习 OpenAPI 规范,在实践中学习会让你掌握得更快更扎实。

Apifox 是区分接口设计和接口运行两个概念的。

接口设计:即 新建接口 界面或接口详情里的 编辑 界面,用途是 定义接口文档规范,而不是 运行 接口,所以该界面是只能定义接口基本信息、参数名及参数说明等,而不能设置参数值。参数值、前置脚本/后置脚本 等信息请在接口运行>界面或接口用例界面填写。

接口运行:即接口详情里的「运行」界面,用途是调试接口,确保你的接口是可以正常运行的。

大家可以体验下,Apifox 对于初学者是非常友好的,可视化的界面让你能够快速的入门 API 设计!

Apifox 导入数据
Apifox 导入数据

知识扩展: