go-swagger – array of objects in request body

Issue

I’m using go-swagger for generating swagger file for our APIs
I’ve been trying to add comments for an API that gets an array of objects in request but the go-swagger seems like is not recognizing it

my request looks like this in JSON format:

{
  [
    {
      "name": "title1",
      "label": "tag1",
      "sort": true
    },
    {
      "name": "title2",
      "label": "tag2",
      "sort": true
    }
  ]
}

this is what my comments looks like right now

// swagger:route POST /admin/qc QC createQC
//
// Creates a new QC.
//
//
//     Consumes:
//     - application/json
//
//     Produces:
//     - application/json
//
//     Schemes: https
//
//     Deprecated: false
//
//
//     Parameters:
//       + name: Authorization
//         in: header
//         required: true
//         type: string
//
//       + name: input
//         in: body
//         required: true
//         type: array
//         items: QC
//
//     Responses:
//       200: StatusOK

this is the generated swagger file

/admin/qc:
    post:
      consumes:
      - application/json
      operationId: createQC
      parameters:
      - in: header
        name: Authorization
        required: true
        type: string
      - in: body
        name: input
        required: true
        schema:
          type: array
      produces:
      - application/json
      responses:
        "200":
          description: StatusOK
          schema:
            $ref: '#/definitions/StatusOK'
      schemes:
      - https
      summary: Creates a new QC.
      tags:
      - QC

the go-swagger does not pick up the items type in this annotation.
the option to change the request type of this API is not available unfortunately.

anybody has any idea how I should annotate this?

Solution

in order to annotate this type of request you will need to define a new struct like this:

// swagger:parameters createQC
type CreateQCReqs struct {
    // in: body
    Body []*CreateQCReq
}

you need to annotate this with swagger:parameters followed by operation id of the api
after that you need to define Body field with your desired data type
in my case it was an array of CreateQCReq
after that you need to remove the body parameter in your swagger:route, otherwise the body field in your swagger file will be generated 2 times

Answered By – Amirreza KN

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.