API的描述語言--Swagger


Swagger是一種Rest API的表示方式。

有時也可以作為Rest API的交互式文檔,描述形式化的接口描述,生成客戶端和服務端的代碼。

 

一,描述語言:Spec

Swagger API Spec是Swagger用來描述Rest API的語言。

API 可以是使用yaml或json來表示。

Swagger API Spec包含以下部分:

swagger,指定swagger spec版本
info,提供API的元數據
tags,補充的元數據,在swagger ui中,用於作為api的分組標簽
host,主機,如果沒有提供,則使用文檔所在的host
basePath,相對於host的路徑
schemes,API的傳輸協議,http,https,ws,wss
consumes,API可以消費的MIME類型列表
produces,API產生的MIME類型列表
paths,API的路徑,以及每個路徑的HTTP方法,一個路徑加上一個HTTP方法構成了一個操作。每個操作都有以下內容: tags,操作的標簽 summary,短摘要 description,描述 externalDocs,外部文檔 operationId,標識操作的唯一字符串 consumes,消費的MIME類型列表 produces,生產的MIME類型列表 parameters,參數列表 responses,應答狀態碼和對於的消息的Schema schemes,傳輸協議 deprecated,不推薦使用 security,安全
definitions,定義API消費或生產的數據類型,使用json-schema描述,操作的parameter和response部分可以通過引用的方式使用definitions部分定義的schema parameters,多個操作共用的參數
responses,多個操作共用的響應
securityDefinitions,安全scheme定義
security,安全聲明
externalDocs,附加的外部文檔

一個操作描述的實例:

/pets/findByTags:
    get:
      tags:
        - pet
      summary: Finds Pets by tags
      description: Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
      operationId: findPetsByTags
      produces:
        - application/json
        - application/xml
      parameters:
        - in: query
          name: tags
          description: Tags to filter by
          required: false
          type: array
          items:
            type: string
          collectionFormat: multi
      responses:
        "200":
          description: successful operation
          schema:
            type: array
            items:
              $ref: "#/definitions/Pet"
        "400":
          description: Invalid tag value
      security:
        - petstore_auth:
          - write_pets
          - read_pets

 

二,Swagger UI

Swagger UI用於顯示Rest接口文檔。

訪問在線Swagger UI:

 

 如何使用?只要把github項目()下載到本地:。然后用瀏覽器打開dist/index.html就可以。

git clone https://github.com/swagger-api/swagger-ui.git

ps:swagger ui支持中文版。方法是修改index.html,在head標簽中添加如下代碼,引入/lang/zh-cn.js

<script src='lang/translator.js' type='text/javascript'></script>
<script src='lang/zh-cn.js' type='text/javascript'></script>

 

三,編輯器

Swagger Editor是Swagger API Spec的編輯器,Swagger Editor使用yaml進行編輯,但允許導入和下載yaml 和 json兩種格式的文件。

下載發布版:

npm install -g http-server
wget https://github.com/swagger-api/swagger-editor/releases/download/v2.10.1/swagger-editor.zip
unzip swagger-editor.zip
http-server -p 8080 swagger-editor

在瀏覽器中輸入地址就可以進行編輯了

 

 

https://zhuanlan.zhihu.com/p/21353795


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM