Swagger 学习笔记及与 Spring Boot 的整合

官方网址:https://swagger.io/

The Best APIs are Built with Swagger Tools

不同服务之间的调用,前端和后端的调用,现在我们都通过 API 接口实现。API 文档成为了不同模块之间联系的纽带,变得越来越重要,Swagger 就是一款让你更好的书写API文档的框架。

目前的开源版本提供三个工具:https://swagger.io/tools/open-source/

  • Swagger Editor 用来设计 OpenAPI
    Design APIs in a powerful editor which visually renders your OpenAPI definition and provides real-time error feedback.
  • Swagger Codegen 用来根据定义的 API 生成不同语言的代码
    Build and enable consumption of your API by generating server stubs and client SDKs with minimal plumbing.
  • Swagger UI 用来产生文档
    Automatically generate documentation from your OpenAPI definition for visual interaction, and easier consumption.

一个示例

假设我们的服务想要提供如下的几个 API 接口:

  • 添加宠物 POST /pet
  • 更新宠物 PUT /pet
  • 查询宠物 GET /pet/{petID}
  • 删除宠物 DELETE /pet/{petID}

输入和输出都支持 JSON 和 XML。

第一步,通过 Swagger Editor 来设计 OpenAPI

地址:https://swagger.io/tools/swagger-editor/

我们输入如下内容:

swagger: '2.0'
info:
  description: >-
    Demo
  version: 1.0.0
  title: Pet Management
  termsOfService: 'http://swagger.io/terms/'
  contact:
    email: [email protected]
  license:
    name: Apache 2.0
    url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
host: petstore.swagger.io
basePath: /v2
tags:
  - name: pet
    description: Everything about your Pets
    externalDocs:
      description: Find out more
      url: 'http://swagger.io'
schemes:
  - https
  - http
paths:
  /pet:
    post:
      tags:
        - pet
      summary: Add a new pet to the store
      description: ''
      operationId: addPet
      consumes:
        - application/json
        - application/xml
      produces:
        - application/xml
        - application/json
      parameters:
        - in: body
          name: body
          description: Pet object that needs to be added to the store
          required: true
          schema:
            $ref: '#/definitions/Pet'
      responses:
        '405':
          description: Invalid input
      security:
        - petstore_auth:
            - 'write:pets'
            - 'read:pets'
    put:
      tags:
        - pet
      summary: Update an existing pet
      description: ''
      operationId: updatePet
      consumes:
        - application/json
        - application/xml
      produces:
        - application/xml
        - application/json
      parameters:
        - in: body
          name: body
          description: Pet object that needs to be added to the store
          required: true
          schema:
            $ref: '#/definitions/Pet'
      responses:
        '400':
          description: Invalid ID supplied
        '404':
          description: Pet not found
        '405':
          description: Validation exception
      security:
        - petstore_auth:
            - 'write:pets'
            - 'read:pets'
  '/pet/{petId}':
    get:
      tags:
        - pet
      summary: Find pet by ID
      description: Returns a single pet
      operationId: getPetById
      produces:
        - application/xml
        - application/json
      parameters:
        - name: petId
          in: path
          description: ID of pet to return
          required: true
          type: integer
          format: int64
      responses:
        '200':
          description: successful operation
          schema:
            $ref: '#/definitions/Pet'
        '400':
          description: Invalid ID supplied
        '404':
          description: Pet not found
      security:
        - api_key: []
    delete:
      tags:
        - pet
      summary: Deletes a pet
      description: ''
      operationId: deletePet
      produces:
        - application/xml
        - application/json
      parameters:
        - name: api_key
          in: header
          required: false
          type: string
        - name: petId
          in: path
          description: Pet id to delete
          required: true
          type: integer
          format: int64
      responses:
        '400':
          description: Invalid ID supplied
        '404':
          description: Pet not found
      security:
        - petstore_auth:
            - 'write:pets'
            - 'read:pets'
securityDefinitions:
  petstore_auth:
    type: oauth2
    authorizationUrl: 'http://petstore.swagger.io/oauth/dialog'
    flow: implicit
    scopes:
      'write:pets': modify pets in your account
      'read:pets': read your pets
  api_key:
    type: apiKey
    name: api_key
    in: header
definitions:
  Category:
    type: object
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string
    xml:
      name: Category
  Tag:
    type: object
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string
    xml:
      name: Tag
  Pet:
    type: object
    required:
      - name
      - photoUrls
    properties:
      id:
        type: integer
        format: int64
      category:
        $ref: '#/definitions/Category'
      name:
        type: string
        example: doggie
      photoUrls:
        type: array
        xml:
          name: photoUrl
          wrapped: true
        items:
          type: string
      tags:
        type: array
        xml:
          name: tag
          wrapped: true
        items:
          $ref: '#/definitions/Tag'
      status:
        type: string
        description: pet status in the store
        enum:
          - available
          - pending
          - sold
    xml:
      name: Pet
  ApiResponse:
    type: object
    properties:
      code:
        type: integer
        format: int32
      type:
        type: string
      message:
        type: string
externalDocs:
  description: Find out more about Swagger
  url: 'http://swagger.io'

编辑的同时在屏幕右侧可以看到对应的 OpenAPI:


Swagger 学习笔记及与 Spring Boot 的整合_第1张图片
对应的 OpenAPI

Swagger 学习笔记及与 Spring Boot 的整合_第2张图片
对应的 OpenAPI

我们将这段内容保存为 YAML 格式(pet.yaml)和 JSON 格式(pet.json):

Swagger 学习笔记及与 Spring Boot 的整合_第3张图片
保存为 YAML 格式(pet.yaml)和 JSON 格式(pet.json)

保存为 YAML 格式(pet.yaml)和 JSON 格式(pet.json)

第二步,通过 Swagger Codegen 用来根据定义的 API 生成不同语言的代码

地址:https://swagger.io/tools/swagger-codegen/

在 Mac 上,先通过 Homebrew 安装 Swagger Codegen:

brew install swagger-codegen

随后我们通过命令来生成代码,具体语法参见 https://github.com/swagger-api/swagger-codegen/wiki/Server-stub-generator-HOWTO#java-springboot
例如 SpringMVC:

java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
  -i http://petstore.swagger.io/v2/swagger.json \
  -l spring --library spring-mvc\
  -o samples/server/petstore/spring-mvc

例如 SpringBoot:

java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
  -i http://petstore.swagger.io/v2/swagger.json \
  -l spring \
  -o samples/server/petstore/springboot

我们也可以通过 Swagger Editor 的网页来直接生成 Server 和 Client 端的 Stub Code:

Swagger 学习笔记及与 Spring Boot 的整合_第4张图片
通过 Swagger Editor 的网页来直接生成 Server 端的 Stub Code

Swagger 学习笔记及与 Spring Boot 的整合_第5张图片
通过 Swagger Editor 的网页来直接生成 Client 端的 Stub Code

Swagger 与 Spring Boot 的整合

参见 Spring Cloud 学习笔记 - No.6 通过 Swagger2 构建 API 文档

你可能感兴趣的:(Swagger 学习笔记及与 Spring Boot 的整合)