目录
前言
顶级标签
元数据
基本网址
标签信息
媒体类型(MIME TYPE)
路径与操作
参数 (parameters)
Common Parameters
同一路径的公共参数
不同路径的公共参数
描述响应体 RequestBody
响应体
空响应体
默认响应
重用响应
完整的Demo Swagger yaml 示例
Swagger 2.0 规范是REST API的API描述格式,API规范可以用YAML或JSON编写,格式易于学习,并且对人和机器都可读,本文主要基于YAML示例 (json 同理试用),其yaml样本如下:
parameters: # 请求体公共参数定义,使用如下格式引用:
# parameters:
# - $ref: "traffic.yaml#/parameters/get-topfc-request"
responses: # 响应体公共参数定义
# schema:
# - $ref: "traffic.yaml#/parameters/get-topfc-request"
definitions: # 定义对象的公共结构
# schema:
# - $ref: "traffic.yaml#/parameters/get-topfc-request"
元数据主要包括一些REST 接口的描述信息,包括如下信息:
# “” 或者 ‘’ 都可以表示值,但是“ ” 不进行 特殊字符转义 ,‘’ 进行特殊字符转义
swagger: "2.0" # 每个Swagger规范都以Swagger版本开始。 2.0 表示 swagger 规范版本
info: # 标题信息
description: "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters." #(此标签可选)
version: "1.0.0" # 表示该rest API版本
title: "Swagger Petstore" #rest api 接口标题名
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" # 为API提供服务的主机的域名或IP地址(IPv4)如果与方案的默认端口(对于HTTP为80,对于HTTPS为443)不同,则它可能包含端口号
# 请注意,必须仅是主机域名和IP地址,不可以包含协议名:http(s)://或 其服务端的子路径。
# 如未指定,则假定为提供API 文档所在的主机
# http://api.example.com (x)
# example.com/api/v1 (x)
basePath: "/v2" #上下文文根 基本网址 必须以"/"开头 相对于主机根目录的所有API路径的URL前缀 不指定默认为"/""
schemes: #请求支持协议 http https wss ws
- "https"
- "http"
tags: # 标签信息
- name: "pet"
description: "Everything about your Pets"
externalDocs:
description: "Find out more"
url: "http://swagger.io"
- name: "store"
description: "Access to Petstore orders"
- name: "user"
description: "Operations about user"
externalDocs:
description: "Find out more about our store"
url: "http://swagger.io"
API接收和返回的数据媒体类型,如常见的 JSON和XML。可以在根级目录定义定义全局媒体类型,其所有API都会继承( inherite) 。而且每一个API 也可以定义自己的媒体类型,会覆盖根级目录定义的。
consumes: # 定义入参值
- application/json
- application/xml
produces: # 定义返回值,及响应数据
- application/json
- application/xml
#consumes和produces 支持 RFC6838标准 包括如下:
application/json
application/xml
application/x-www-form-urlencoded
multipart/form-data
text/plain
charset=utf-8
text/html
application/pdf
image/png
# 以及一些特定供应商的MIMETYPE
application/vnd.mycompany.myapp.v2+json
application/vnd.ms-excel
application/vnd.openstreetmap.data+xml
application/vnd.github-issue.text+json
application/vnd.github.v3.diff
image/vnd.djvu
paths 部分定义了API 中路径、端点,及其支持的http 或 wss方法,所有方法都是相对路径。
paths:
/ping: # 必须以"/" 开头 支持模板定义 可以使用大括号{}将URL的一部分标记为路径参数
# /organizations/{orgId}/members/{memberId}
# 操作方式: swagger 2.0 支持 get,post,put,patch,delete,head,options 操作
# 每个路径支持多个操作方式。
# Swagger将路径和操作方式定义为唯一操作。(重点理解)
# 意味着不允许使用同一路径的两个GET或POST方法-即使它们具有不同的参数(参数对唯一性没有影响)
GET /users?firstName=value&lastName=value
GET /users?role=value
# 以上两个url 代表同一个操作,不允许这样定义
#正确的是如下所示:
GET /users/findByName?firstName=value&lastName=value
GET /users/findByRole?role=value
# 路径里面不允许包含查询字符串参数 ,其查询参数应该定义在parameters:结构里
# /users?role={role} (x)
#正确的是如下结构:
/users:
get:
parameters:
- in: query
name: role
type: string
enum: [user, poweruser, admin]
required: false
parameters:
- in: query # "-" 表示列表元素,parameters 是一个list,所以每一个参数都需要携带"-"
# 参数位置 表示该参数位于 api 那个部分 可以有path query body header form
# query: 查询参数,例如/users?role=1&limit=50 只支持基本数据类型,可以是array,但是item必须是基本数据类型
# path: 路径参数,例如/users/{id}
# body: 请求体参数,post put patch 请求主体参数
# header: http 请求头参数,例如X-MyHeader: Value
# formData:表单参数
name: role
type: integer
required: true
description: Numeric ID of the user to get.
- in: query
name: limit
default: 0 # 默认值
minimum: 1 # 最小值
maximum: 100 # 最大值
enum: [1,20,50,100]
type: integer
- in: path # 例如 /users/{id} /cars/{carId}/drivers/{driverId}
#/users/12,34,56 可以是多个值,定义为array
name: id
type: integer
required: true # 路径参数要求必须是true
- in: header # http 请求头参数
name: X-Request-ID
type: string
- in: formData #
name: name
type: string
description: A person's name.
- in: query
name: color
type: array
collectionFormat: csv # arry 转换url后分隔符定义
items:
type: string
enum: [black, white, gray] # 将列表值限定为枚举值
# Path, query, header and form parameters 都可以接受列表参数
GET /users/12,34,56,78 # path url
GET /resource?param=value1,value2,value3 # query url
GET /resource?param=value1¶m=value2¶m=value3 # query url
POST /resource # header
param=value1¶m=value2 #form
公共参数,和MIME TYPE 一样,全局公共参数可以在path 下定义,则关于该path下的所有operation都可以适应该参数,并且每一个operation 可以覆盖去全局公共参数,也可以添加自己独有的参数。但不可以移除公共参数
paths:
/user/{id}:
parameters: # 全局公共参数
- in: path
name: id
type: integer
required: true
description: The user ID.
get:
summary: Gets a user by ID.
parameters: # get operation 特有参数
- in: query
name: metadata
type: boolean
required: false
description: If true, the endpoint returns only the user metadata.
responses:
200:
description: OK
patch:
summary: Updates an existing user with the specified ID.
parameters: # patch operation 可以覆盖全局参数
- in: path
name: id
required: true
description: A comma-separated list of user IDs.
type: array
items:
type: integer
collectionFormat: csv
minItems: 1
responses:
200:
description: OK
delete:
summary: Deletes the user with the specified ID.
可以在全局公共参数里面定义结构,采用$ref 引用该结构
parameters: # 定义公共参数
offsetParam: # <-- Arbitrary name for the definition that will be used to refer to it.
# Not necessarily the same as the parameter name.
in: query
name: offset
required: false
type: integer
minimum: 0
description: The number of items to skip before starting to collect the result set.
paths:
/users:
get:
summary: Gets a list of users.
parameters:
- $ref: '#/parameters/offsetParam'
responses:
200:
description: OK
/teams:
get:
summary: Gets a list of teams.
parameters:
- $ref: '#/parameters/offsetParam'
responses:
200:
description: OK
paths:
/users:
post:
summary: Creates a new user.
consumes:
- application/json
parameters:
- in: body
name: user
description: The user to create.
schema: # 定义响应体 或者 请求体
type: object
required:
- userName
properties: # object 类型的属性列表,目测可以不添加“-”
userName:
type: string
firstName:
type: string
lastName:
type: string
responses:
201:
description: Created
# 或者"definitions" 定义响应体公共结构 使用 $ref 引用
paths:
/users:
post:
summary: Creates a new user.
consumes:
- application/json
parameters:
- in: body
name: user
description: The user to create.
schema:
$ref: '#/definitions/User' # <----------
responses:
200:
description: OK
definitions:
User: # <----------
type: object
required:
- userName
properties:
userName:
type: string
firstName:
type: string
lastName:
type: string
produces:
- application/json
paths:
# This operation returns JSON - as defined globally above
/users:
get:
summary: Gets a list of users.
responses:
200:
description: OK
# Here, we override the "produces" array to specify other media types
/logo:
get:
summary: Gets the logo image.
produces: # 定义特殊响应体 媒体类型
- image/png
- image/gif
- image/jpeg
responses:
200: # 定义一个状态码
description: OK # 状态码必须有描述
schema: # 定义响应体结构 或者用 definitions:定义公共响应体
type: object
properties:
id:
type: integer
description: The user ID.
username:
type: string
description: The user name.
# 某些响应(204 No Content)没有正文。为了表示响应主体为空,不定义schema结构即可。swagger会认为空响应体
responses:
204:
description: ok
responses:
200:
description: Success
schema:
$ref: '#/definitions/User'
# Definition of all error statuses
default: # 表示 此响应码为没有单独覆盖的http状态码,统一返回此响应体
description: Unexpected error
schema:
$ref: '#/definitions/Error'
paths:
/users:
get:
summary: Gets a list of users.
response:
200:
description: OK
schema:
$ref: '#/definitions/ArrayOfUsers'
401:
$ref: '#/responses/Unauthorized' # <-----
/users/{id}:
get:
summary: Gets a user by ID.
response:
200:
description: OK
schema:
$ref: '#/definitions/User'
401:
$ref: '#/responses/Unauthorized' # <-----
404:
$ref: '#/responses/NotFound' # <-----
# Descriptions of common responses
responses: # 定义全局响应体,可以使用$ref 引用
NotFound:
description: The specified resource was not found
schema:
$ref: '#/definitions/Error'
Unauthorized:
description: Unauthorized
schema:
$ref: '#/definitions/Error'
definitions: # 定义全局body体结构,可以使用$ref 引用
# Schema for error response body
Error:
type: object
properties:
code:
type: string
message:
type: string
required:
- code
- message
swagger: "2.0"
info:
description: "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters."
version: "1.0.0"
title: "Swagger Petstore"
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"
- name: "store"
description: "Access to Petstore orders"
- name: "user"
description: "Operations about user"
externalDocs:
description: "Find out more about our store"
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/findByStatus:
get:
tags:
- "pet"
summary: "Finds Pets by status"
description: "Multiple status values can be provided with comma separated strings"
operationId: "findPetsByStatus"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "status"
in: "query"
description: "Status values that need to be considered for filter"
required: true
type: "array"
items:
type: "string"
enum:
- "available"
- "pending"
- "sold"
default: "available"
collectionFormat: "multi"
responses:
"200":
description: "successful operation"
schema:
type: "array"
items:
$ref: "#/definitions/Pet"
"400":
description: "Invalid status value"
security:
- petstore_auth:
- "write:pets"
- "read:pets"
/pet/findByTags:
get:
tags:
- "pet"
summary: "Finds Pets by tags"
description: "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing."
operationId: "findPetsByTags"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "tags"
in: "query"
description: "Tags to filter by"
required: true
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"
deprecated: true
/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: []
post:
tags:
- "pet"
summary: "Updates a pet in the store with form data"
description: ""
operationId: "updatePetWithForm"
consumes:
- "application/x-www-form-urlencoded"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "petId"
in: "path"
description: "ID of pet that needs to be updated"
required: true
type: "integer"
format: "int64"
- name: "name"
in: "formData"
description: "Updated name of the pet"
required: false
type: "string"
- name: "status"
in: "formData"
description: "Updated status of the pet"
required: false
type: "string"
responses:
"405":
description: "Invalid input"
security:
- petstore_auth:
- "write:pets"
- "read:pets"
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"
/pet/{petId}/uploadImage:
post:
tags:
- "pet"
summary: "uploads an image"
description: ""
operationId: "uploadFile"
consumes:
- "multipart/form-data"
produces:
- "application/json"
parameters:
- name: "petId"
in: "path"
description: "ID of pet to update"
required: true
type: "integer"
format: "int64"
- name: "additionalMetadata"
in: "formData"
description: "Additional data to pass to server"
required: false
type: "string"
- name: "file"
in: "formData"
description: "file to upload"
required: false
type: "file"
responses:
"200":
description: "successful operation"
schema:
$ref: "#/definitions/ApiResponse"
security:
- petstore_auth:
- "write:pets"
- "read:pets"
/store/inventory:
get:
tags:
- "store"
summary: "Returns pet inventories by status"
description: "Returns a map of status codes to quantities"
operationId: "getInventory"
produces:
- "application/json"
parameters: []
responses:
"200":
description: "successful operation"
schema:
type: "object"
additionalProperties:
type: "integer"
format: "int32"
security:
- api_key: []
/store/order:
post:
tags:
- "store"
summary: "Place an order for a pet"
description: ""
operationId: "placeOrder"
produces:
- "application/xml"
- "application/json"
parameters:
- in: "body"
name: "body"
description: "order placed for purchasing the pet"
required: true
schema:
$ref: "#/definitions/Order"
responses:
"200":
description: "successful operation"
schema:
$ref: "#/definitions/Order"
"400":
description: "Invalid Order"
/store/order/{orderId}:
get:
tags:
- "store"
summary: "Find purchase order by ID"
description: "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions"
operationId: "getOrderById"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "orderId"
in: "path"
description: "ID of pet that needs to be fetched"
required: true
type: "integer"
maximum: 10.0
minimum: 1.0
format: "int64"
responses:
"200":
description: "successful operation"
schema:
$ref: "#/definitions/Order"
"400":
description: "Invalid ID supplied"
"404":
description: "Order not found"
delete:
tags:
- "store"
summary: "Delete purchase order by ID"
description: "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors"
operationId: "deleteOrder"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "orderId"
in: "path"
description: "ID of the order that needs to be deleted"
required: true
type: "integer"
minimum: 1.0
format: "int64"
responses:
"400":
description: "Invalid ID supplied"
"404":
description: "Order not found"
/user:
post:
tags:
- "user"
summary: "Create user"
description: "This can only be done by the logged in user."
operationId: "createUser"
produces:
- "application/xml"
- "application/json"
parameters:
- in: "body"
name: "body"
description: "Created user object"
required: true
schema:
$ref: "#/definitions/User"
responses:
default:
description: "successful operation"
/user/createWithArray:
post:
tags:
- "user"
summary: "Creates list of users with given input array"
description: ""
operationId: "createUsersWithArrayInput"
produces:
- "application/xml"
- "application/json"
parameters:
- in: "body"
name: "body"
description: "List of user object"
required: true
schema:
type: "array"
items:
$ref: "#/definitions/User"
responses:
default:
description: "successful operation"
/user/createWithList:
post:
tags:
- "user"
summary: "Creates list of users with given input array"
description: ""
operationId: "createUsersWithListInput"
produces:
- "application/xml"
- "application/json"
parameters:
- in: "body"
name: "body"
description: "List of user object"
required: true
schema:
type: "array"
items:
$ref: "#/definitions/User"
responses:
default:
description: "successful operation"
/user/login:
get:
tags:
- "user"
summary: "Logs user into the system"
description: ""
operationId: "loginUser"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "username"
in: "query"
description: "The user name for login"
required: true
type: "string"
- name: "password"
in: "query"
description: "The password for login in clear text"
required: true
type: "string"
responses:
"200":
description: "successful operation"
schema:
type: "string"
headers:
X-Rate-Limit:
type: "integer"
format: "int32"
description: "calls per hour allowed by the user"
X-Expires-After:
type: "string"
format: "date-time"
description: "date in UTC when token expires"
"400":
description: "Invalid username/password supplied"
/user/logout:
get:
tags:
- "user"
summary: "Logs out current logged in user session"
description: ""
operationId: "logoutUser"
produces:
- "application/xml"
- "application/json"
parameters: []
responses:
default:
description: "successful operation"
/user/{username}:
get:
tags:
- "user"
summary: "Get user by user name"
description: ""
operationId: "getUserByName"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "username"
in: "path"
description: "The name that needs to be fetched. Use user1 for testing. "
required: true
type: "string"
responses:
"200":
description: "successful operation"
schema:
$ref: "#/definitions/User"
"400":
description: "Invalid username supplied"
"404":
description: "User not found"
put:
tags:
- "user"
summary: "Updated user"
description: "This can only be done by the logged in user."
operationId: "updateUser"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "username"
in: "path"
description: "name that need to be updated"
required: true
type: "string"
- in: "body"
name: "body"
description: "Updated user object"
required: true
schema:
$ref: "#/definitions/User"
responses:
"400":
description: "Invalid user supplied"
"404":
description: "User not found"
delete:
tags:
- "user"
summary: "Delete user"
description: "This can only be done by the logged in user."
operationId: "deleteUser"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "username"
in: "path"
description: "The name that needs to be deleted"
required: true
type: "string"
responses:
"400":
description: "Invalid username supplied"
"404":
description: "User not found"
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:
Order:
type: "object"
properties:
id:
type: "integer"
format: "int64"
petId:
type: "integer"
format: "int64"
quantity:
type: "integer"
format: "int32"
shipDate:
type: "string"
format: "date-time"
status:
type: "string"
description: "Order Status"
enum:
- "placed"
- "approved"
- "delivered"
complete:
type: "boolean"
default: false
xml:
name: "Order"
Category:
type: "object"
properties:
id:
type: "integer"
format: "int64"
name:
type: "string"
xml:
name: "Category"
User:
type: "object"
properties:
id:
type: "integer"
format: "int64"
username:
type: "string"
firstName:
type: "string"
lastName:
type: "string"
email:
type: "string"
password:
type: "string"
phone:
type: "string"
userStatus:
type: "integer"
format: "int32"
description: "User Status"
xml:
name: "User"
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"