我定义了一个以MyObject作为参数的路径。 MyObject具有猫和狗的属性。这些都有默认值。 在swagger-editor中,该示例未显示默认值,但try-it-out确实创建了具有正确默认值的MyObject。
在swagger-ui中,我可以在模型下看到默认值,但在API中看不到。有没有办法设置这些默认值? 招摇:'2.0' 信息: title:使用默认属性作为参数传递对象 描述:等 版本:“草案0.1.1” 主持人:example.com basePath:/ 生产: - application / json
paths:
/myobject:
post:
summary: |
post an object.
parameters:
- name: myObject
in: body
required: true
schema:
type: array
items:
$ref: '#/definitions/MyObject'
responses:
200:
description: OK
definitions:
MyObject: # move to/models/model.yml
type: object
description: Contains default properties
required:
- cats
- dogs
properties:
cats:
type: number
default: 9
dogs:
type: string
default: "fido"
答案 0 :(得分:5)
您对default
的使用是错误的。您可能需要example
。
default
仅用于可选字段,在服务器端处理。也就是说,如果客户端没有在有效负载中提供值,则服务器将使用default
值。
考虑这个User
模型:
definitions:
User:
type: object
required:
- username
properties:
username:
type: string
role:
type: string
enum:
- user
- poweruser
- admin
default: user
role
属性是可选的,默认为user
。因此,如果客户端发送的负载没有role
:
{
"username": "bob"
}
服务器将假设role
= user
。
在您的情况下,您似乎想要为字段提供示例值。这是example
关键字的用途:
definitions:
MyObject:
type: object
description: Contains default properties
required:
- cats
- dogs
properties:
cats:
type: number
example: 9 # <---
dogs:
type: string
example: fido # <---
答案 1 :(得分:0)
似乎有两种默认设置:
对于客户端默认值,我们可以通过将required = True设置为枚举并将其枚举为唯一的允许值。请参见下面的示例:
swagger: "2.0"
info:
title: "some api"
description: "a description"
version: "1.0.0"
host: "example.com"
basePath: "/api"
schemes:
- "http"
paths:
/myobject:
post:
summary: |
post an object.
parameters:
- name: myObject
in: body
required: true
schema:
type: array
items:
$ref: '#/definitions/MyObject'
responses:
200:
description: OK
definitions:
MyObject:
type: object
description: Contains default properties
required:
- cats
- dogs
properties:
cats:
type: number
enum:
- 9
dogs:
type: string
enum:
- fido
您可以在此处的swagger-editor中看到它的工作原理:https://editor.swagger.io/
默认参数有点令人困惑,因为swagger 2.0最初描述了默认参数而未指定服务器或客户端参考框架。
Swagger 2.0 spec 定义架构默认为
default (Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object)
default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if type is string, then default can be "foo" but cannot be 1.