Swagger 學(xué)習(xí)筆記及與 Spring Boot 的整合

官方網(wǎng)址:https://swagger.io/

The Best APIs are Built with Swagger Tools

不同服務(wù)之間的調(diào)用,前端和后端的調(diào)用,現(xiàn)在我們都通過 API 接口實(shí)現(xiàn)。API 文檔成為了不同模塊之間聯(lián)系的紐帶,變得越來越重要,Swagger 就是一款讓你更好的書寫API文檔的框架。

目前的開源版本提供三個(gè)工具:https://swagger.io/tools/open-source/

  • Swagger Editor 用來設(shè)計(jì) OpenAPI
    Design APIs in a powerful editor which visually renders your OpenAPI definition and provides real-time error feedback.
  • Swagger Codegen 用來根據(jù)定義的 API 生成不同語言的代碼
    Build and enable consumption of your API by generating server stubs and client SDKs with minimal plumbing.
  • Swagger UI 用來產(chǎn)生文檔
    Automatically generate documentation from your OpenAPI definition for visual interaction, and easier consumption.

一個(gè)示例

假設(shè)我們的服務(wù)想要提供如下的幾個(gè) API 接口:

  • 添加寵物 POST /pet
  • 更新寵物 PUT /pet
  • 查詢寵物 GET /pet/{petID}
  • 刪除寵物 DELETE /pet/{petID}

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

第一步,通過 Swagger Editor 來設(shè)計(jì) OpenAPI

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

我們輸入如下內(nèi)容:

swagger: '2.0'
info:
  description: >-
    Demo
  version: 1.0.0
  title: Pet Management
  termsOfService: 'http://swagger.io/terms/'
  contact:
    email: apiteam@swagger.io
  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'

編輯的同時(shí)在屏幕右側(cè)可以看到對(duì)應(yīng)的 OpenAPI:


對(duì)應(yīng)的 OpenAPI

對(duì)應(yīng)的 OpenAPI

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

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

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

第二步,通過 Swagger Codegen 用來根據(jù)定義的 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 的網(wǎng)頁來直接生成 Server 和 Client 端的 Stub Code:

通過 Swagger Editor 的網(wǎng)頁來直接生成 Server 端的 Stub Code

通過 Swagger Editor 的網(wǎng)頁來直接生成 Client 端的 Stub Code

Swagger 與 Spring Boot 的整合

參見 Spring Cloud 學(xué)習(xí)筆記 - No.6 通過 Swagger2 構(gòu)建 API 文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swagger 是一個(gè)統(tǒng)一前后端用于生成文檔和代碼的工具,它使用 yaml / json 作為描述語言 通過 Op...
    連續(xù)三屆村草閱讀 43,265評(píng)論 2 17
  • afinalAfinal是一個(gè)android的ioc,orm框架 https://github.com/yangf...
    wgl0419閱讀 6,575評(píng)論 1 9
  • 被放任了一段“關(guān)系”,已經(jīng)沒辦法再滿懷期待的等下去,特別可笑的發(fā)了微信漂流瓶,對(duì)著畫面上的不怎么真實(shí)的大海,拋出了...
    50歲再見閱讀 295評(píng)論 0 0
  • 北方的深冬,總是莫名的蕭瑟孤寂,一場(chǎng)漫無邊際的雪鋪天蓋地,一個(gè)月的時(shí)間都沒曾將痕跡消散,城外的樹林田野,點(diǎn)點(diǎn)斑白,...
    菀彼青青閱讀 603評(píng)論 6 8
  • 我想我的這份感情可能要走到盡頭了。 情深不壽,慧極必傷。 以前是不太懂這兩句話的。都道是深情不渝,何來情深不壽呢?...
    藍(lán)青櫻閱讀 660評(píng)論 4 5

友情鏈接更多精彩內(nèi)容