2

Swagger 2 和 Open API 3 的区别

 2 years ago
source link: https://liqiang.io/post/openapi-30-vs-swagger-20?lang=ZH_CN
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在写 API 文档的时候,可能你有其他选择,但是你很可能会选择或者考虑过 Swagger,但是它现在已经不叫 Swagger 了,而是捐赠给了 Linux 基金会称为了 Open API,所以本文就对比一下他们做了哪些改变。

其实从概述上看,其实 3.0 比 2.0 来说,重要的特点就是变得更抽象了,然后更加地组件化了,一张图来看是这样的:

72b0f4a580a1

所以下面就具体看下变化吧。

元数据的变化

所有对 swagger 的引用都被改为 openapi,这个是最直观的,第一行就需要改变。因此版本必须要有如下变化:

  1. [[email protected]]# cat docs.yaml
  2. "swagger": "2.0"
  3. -->
  4. "openapi": "3.0.0"

Server 定义变化

以前旧版本的长这样:

  1. [[email protected]]# cat v2-docs.yaml
  2. host: example.com
  3. basePath: /v1
  4. schemes: ['http', 'https']

新版本可以长这样:

  1. [[email protected]]# cat v3-docs.yaml
  2. servers:
  3. - url: https://{subdomain}.site.com/{version}
  4. description: The main prod server
  5. variables:
  6. subdomain:
  7. default: production
  8. version:
  9. enum:
  10. - v1
  11. - v2
  12. default: v2

旧版本的请求无论是在 path 还是在 header 上,都是混在一起的,在 openapi 3 上将他们分开了:

  1. [[email protected]]# cat v2-docs.yaml
  2. "/pets/{petId}":
  3. post:
  4. parameters:
  5. - name: petId
  6. in: path
  7. description: ID of pet to update
  8. required: true
  9. type: string
  10. - name: user
  11. in: body
  12. description: user to add to the system
  13. required: true
  14. schema:
  15. type: array
  16. items:
  17. type: string

在 v3 的时候更加明确了:

  1. [[email protected]]# cat v3-docs.yaml
  2. "/pets/{petId}":
  3. post:
  4. requestBody:
  5. description: user to add to the system
  6. required: true
  7. content:
  8. application/json:
  9. schema:
  10. type: array
  11. items:
  12. $ref: '#/components/schemas/Pet'
  13. examples:
  14. - name: Fluffy
  15. petType: Cat
  16. - http://example.com/pet.json
  17. parameters:
  18. - name: petId
  19. in: path
  20. description: ID of pet to update
  21. required: true
  22. type: string

Security 变化

其实这个我还是没法直接看懂怎么用:

  1. [[email protected]]# cat v2-docs.yaml
  2. securityDefinitions:
  3. UserSecurity:
  4. type: basic
  5. APIKey:
  6. type: apiKey
  7. name: Authorization
  8. in: header
  9. security:
  10. - UserSecurity: []
  11. - APIKey: []

—> 新版本:

  1. [[email protected]]# cat v3-docs.yaml
  2. components:
  3. securitySchemes:
  4. UserSecurity:
  5. type: http
  6. scheme: basic
  7. APIKey:
  8. type: http
  9. scheme: bearer
  10. bearerFormat: TOKEN
  11. security:
  12. - UserSecurity: []
  13. - APIKey: []

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK