Swagger 學習筆記及與 Spring Boot 的整合

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:

 

對應的 OpenAPI

 

對應的 OpenAPI

我們將這段內容保存爲 YAML 格式(pet.yaml)和 JSON 格式(pet.json):

保存爲 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 Editor 的網頁來直接生成 Server 端的 Stub Code

 

通過 Swagger Editor 的網頁來直接生成 Client 端的 Stub Code

 

Swagger 與 Spring Boot 的整合

參見 Spring Cloud 學習筆記 - No.6 通過 Swagger2 構建 API 文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章