0

Swagger ignoring required fields in body of POST request.

Steps to reproduce:

  1. Describe 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. Generate api

swagger generate server -f swaggerfile.yaml -t api

  1. Describe single handler:
api.UserCreateHandler = operations.UserCreateHandlerFunc(func(params operations.UserCreateParams) middleware.Responder {
        return middleware.NotImplemented("MUST NOT BE PRINTED")
    })
  1. Make a request to generated api:

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

Expected result:

400 Bad Request

Given result:

501 MUST NOT BE PRINTED

Vadim Filin
  • 342
  • 3
  • 12

1 Answers1

0

My personal workaround is

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")
    })

Vadim Filin
  • 342
  • 3
  • 12