Swagger是一種Rest API的表示方式。javascript
有時也能夠做爲Rest API的交互式文檔,描述形式化的接口描述,生成客戶端和服務端的代碼。html
一,描述語言:Specjava
Swagger API Spec是Swagger用來描述Rest API的語言。node
API 能夠是使用yaml或json來表示。git
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,附加的外部文檔
一個操做描述的實例:github
/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 UInpm
Swagger UI用於顯示Rest接口文檔。json
訪問在線Swagger UI:http://petstore.swagger.io/api
如何使用?只要把github項目(https://github.com/swagger-api/swagger-ui)下載到本地:。而後用瀏覽器打開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兩種格式的文件。
下載發佈版:https://github.com/swagger-api/swagger-editor/releases/download/v2.10.1/swagger-editor.zip
解壓,而後用HTTP Server將靜態文件加載起來,下面是安裝node.js的http server並跑起來的指令
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