REST API 参数是否应该影响其他需要的参数?
Should a REST API parameter ever influence which other parameters are required?
例如,我可以创建一个交通工具,并且必须给它一个可以是 "automobile" 或 "airplane" 的类型。汽车需要轮胎尺寸参数,飞机需要翼展参数。关于 REST API 参数是否应该影响响应中需要哪些属性的类似问题。
/vehicles:
post:
summary: Creates a vehicle
description: Adds a new vehicle of given type.
parameters:
- name: vehicle (what is the purpose of this????)
in: body
description: The vehicle to create.
schema:
required:
- type
- speed
- color
properties:
type:
type: string
speed:
type: interger
color:
type: string
wingspan:
type: string
tiresize:
type: string
responses:
204:
description: Vehicle succesfully created.
400:
description: Vehicle couldn't have been created.
虽然这种情况在实践中会发生,但最好避免,因为它很难记录您的 API。如果您使用不允许这些 "conditionally required" 参数的文档技术(例如 Swagger),则尤其如此。通过添加它们,您实际上是在向您的 API 添加额外的语义,这在 Swagger 文档中没有记录。
更好的方法是,不要使用不同车辆类型的 "type" 参数,而是为每种类型使用单独的 URL。这将允许您正确记录每种车辆类型的 required/optional 参数。
/vehicles/automobile:
post:
parameters:
schema:
required:
- tyresize
properties:
tyresize:
type: string
/vehicles/airplane:
post:
parameters:
schema:
required:
- wingspan
properties:
wingspan:
type: string
例如,我可以创建一个交通工具,并且必须给它一个可以是 "automobile" 或 "airplane" 的类型。汽车需要轮胎尺寸参数,飞机需要翼展参数。关于 REST API 参数是否应该影响响应中需要哪些属性的类似问题。
/vehicles:
post:
summary: Creates a vehicle
description: Adds a new vehicle of given type.
parameters:
- name: vehicle (what is the purpose of this????)
in: body
description: The vehicle to create.
schema:
required:
- type
- speed
- color
properties:
type:
type: string
speed:
type: interger
color:
type: string
wingspan:
type: string
tiresize:
type: string
responses:
204:
description: Vehicle succesfully created.
400:
description: Vehicle couldn't have been created.
虽然这种情况在实践中会发生,但最好避免,因为它很难记录您的 API。如果您使用不允许这些 "conditionally required" 参数的文档技术(例如 Swagger),则尤其如此。通过添加它们,您实际上是在向您的 API 添加额外的语义,这在 Swagger 文档中没有记录。
更好的方法是,不要使用不同车辆类型的 "type" 参数,而是为每种类型使用单独的 URL。这将允许您正确记录每种车辆类型的 required/optional 参数。
/vehicles/automobile:
post:
parameters:
schema:
required:
- tyresize
properties:
tyresize:
type: string
/vehicles/airplane:
post:
parameters:
schema:
required:
- wingspan
properties:
wingspan:
type: string