Search code examples
python-3.xapiflaskswaggerflask-restplus

Swagger API documentation and flask-restplus: How to represent an object with a key in the body of a request


I have this example of the parameter needed in the body of a PUT request to my API:

{
  "id": "string",
  "closed_date": "2018-11-20T18:42:58.946Z",
  "contact": "string",
  "description": "string",
  "status": "Open"
}

To have it represented in my Swagger end point documentation I did this :

@api.doc(body=card_change_fields)
    def put(self, card_id, *args, **kwargs):

Where:

card_change_fields = api.model('card modification', {

        'id': fields.String(description='id', required=True),
        'closed_date': fields.DateTime(description='Closed date'),
        'contact': fields.String(description='Contact'),
        'description': fields.String(description='Description'),
        'status': fields.String(description='Status', required=True,
                                enum=["Open", "Closed"])
})

However what I want is actually this :

{  card : {
  "id": "string",
  "closed_date": "2018-11-20T18:42:58.946Z",
  "contact": "string",
  "description": "string",
  "status": "Open" }
}

How can I do this in my flask-restplus swagger documentation ? I tried with child and parent model and expect with no success

Thanks, DT


Solution

  • You need to use fields.Nested to use a model to be a input of another Model. Check the code below:

    card_change_fields = api.model('card modification', {
                    'id': fields.String(description='id', required=True),
                    'closed_date': fields.DateTime(description='Closed date'),
                    'contact': fields.String(description='Contact'),
                    'description': fields.String(description='Description'),
                    'status': fields.String(description='Status', required=True,
                                            enum=["Open", "Closed"])
    })
    
    card = api.model('Card', {
        'card': fields.Nested(card_change_fields, required=True)
    })
    

    And respectively your doc rendering will also change to:

    @api.doc(body=card)
        def put(self, card_id, *args, **kwargs):