2

I am developing an API using flask-restplus. One of my endpoint returns a list of object, e.g.

[
  {
    "id": "1342",
    "index": "meta",
    "score": 3.0630198
  },
  {
    "id": "1645",
    "index": "meta",
    "score": 3.0630198
  },
  {
    "id": "2345",
    "index": "meta",
    "score": 3.0630198
  }
]

Now I am trying to develop a model using fields so I can marshal it as a result of get, e.g

model = namespace.model('MyModel', {
    "some_attribute":fields.List(fields.Nested(some_nested_object))
})

@namespace.route('')
class FlashcardAutocompleteAPI(Resource):
...
   @namespace.marshal_with(model,code=200)
   def get(self):
      ...

The above code of course works, but does not marshal the correct structure.

Is there any way to NOT declare the "some_attribute" part, such that the model would marshal the json structure as provided above? Trying this:

 model = namespace.model('MyModel', {
    fields.List(fields.Nested(some_nested_object))
})

I receive:

  TypeError: cannot convert dictionary update sequence element #0 to a 
  sequence

2 Answers2

2

not sure if this helps, I had a similar problem but with the post method instead of get. In this case I had the expect decorator before the method

@ns.expect(model, validate=True)

and it worked if I just wrap the model with brackets, like so:

@ns.expect([model] validate=True)

The solution was pointed out in https://github.com/noirbizarre/flask-restplus/issues/230

I know this is just a partial answer, but maybe sheds some light on the issue. Good luck!

mgfernan
  • 783
  • 2
  • 8
  • 21
0

You don't need to declare a new model, flask-restplus can reuse the same model described by some_nested_object to marshall either a single item or a list of items of that type.

So you just need to write something like this:

@namespace.route('')
class FlashcardAutocompleteAPI(Resource):
...
   @namespace.marshal_with(some_nested_object,code=200)
   def get(self):
      items = build_object_list()
      return items
morpheuz
  • 91
  • 1
  • 10