gamda
gamda

Reputation: 580

Flask-Restful-Swagger Model class with List field

I am currently building the docs for an API using Flask-Restful-Swagger. One of my resources return a dict with one element: an array. The items in the array are of the form

{
  "active": bool,
  "affectation": str,
  "alert_type": str, ...
} 

and so on. The fields are bool, str, int, or float. There are a total of 32 fields in each element of the array. I am trying to build the @swagger.model class to use as responseClass.

First I tried:

@swagger.model
class ReportListGet:
    resource_fields = {
        'items': fields.List(fields.String)
    }

which produced the expected output on the HTML view of Swagger:

{
  "items": [
    ""
  ]
}

So I tried to build on top of it to show the actual response. Something like:

{
  "items": [
    {
       "active": fields.Boolean,
       "affectation": fields.String,
       "alert_type": fields.String, ...
    }
  ]
}

My second attempt was to create a dictionary with all the fields and then use fields.Nested like:

resource_fields = {
    'items': fields.List(fields.Nested(report_fields))
}

but the output in the HTML was

{
    "items": [
        null
    ]
}

Then I tried to create my own field inheriting from fields.Raw but it gave me the same null dict on the HTML. Assigning default values to the fields didn't work either.

Upvotes: 1

Views: 3704

Answers (1)

gamda
gamda

Reputation: 580

I figured it out!

The main class ended up like this:

@swagger.model
@swagger.nested(
    items=Report.__name__)
class ReportListGet:
    resource_fields = {
        'items': fields.List(fields.Nested(Report.resource_fields))
    }

The other class is just a regular @swagger.model:

@swagger.model
class Report:
    resource_fields = {
        "active": fields.String,
        "affectation": fields.String,
        "alert_type": fields.String,
        ...
    }

Found the clues I needed in the examples from Restful-Flask-Swagger's GitHub page. Useful code starts at line 157.

Now the HTML view of Swagger shows this:

{
  "items": [
    {
      "active": "",
      "affectation": "",
      "alert_type": "",
      ...
    }
  ]
}

Upvotes: 2

Related Questions