0

Swagger 忽略 POST 请求正文中的必填字段。

重现步骤:

  1. 描述 swaggerfile
swagger: "2.0"
info:
  title: Sample API
  description: API description in Markdown.
  version: 1.0.0
host: api.example.com
schemes:
  - http
paths:
  /users:
    post:
      operationId: UserCreate
      parameters:
        - name: body
          in: body
          required: true
          schema:
            allOf:
              - $ref: "#/definitions/ID"
              - $ref: "#/definitions/User_object"
              - type: object
                required:  # HERE! IT IS NOT WORKING
                  - ID
                  - genderCode
                  - birthDate
                  - code
      produces:
        - application/json
      consumes:
        - application/json
      responses:
        200:
          description: "OK"

definitions:
  ID:
    title: ID
    properties:
      GUID:
        type: string
        description: "ID"
        format: uuid

  User_object:
    title: User_object
    properties:
      genderCode:
        type: string
      birthDate:
        type: string
        format: date
      code:
        type: string
  1. 生成api

招摇生成服务器 -f swaggerfile.yaml -t api

  1. 描述单个处理程序:
api.UserCreateHandler = operations.UserCreateHandlerFunc(func(params operations.UserCreateParams) middleware.Responder {
        return middleware.NotImplemented("MUST NOT BE PRINTED")
    })
  1. 向生成的 api 发出请求:

curl -X POST -H "Content-Type: application/json" -d '{"foo":"bar"}' localhost:{{host}}/users

预期结果:

400 错误请求

给定结果:

501 不得打印

4

1 回答 1

0

我个人的解决方法是

api.UserCreateHandler = operations.UserCreateHandlerFunc(func(params operations.UserCreateParams) middleware.Responder {
        if params.Body.UserObject == (models.UserObject{}) {
            return //... your BAD REQUEST type
        }
        return middleware.NotImplemented("MUST NOT BE PRINTED")
    })

于 2019-05-22T22:06:41.330 回答