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