Search code examples
flaskmarshallingflask-restful

Marshaling items in lists using flask restful


I am writing a Flask-RESTFUL resource. It returns a Model object called DocumentSet with the following structure:

DocumentSet:
id: int
documents: list of Document

Document is another Model object with the following structure:

Document:
id: int
...other fields...

I want to write a @marshal_with decorator that returns the DocumentSet id along with a list of the Document ids like so:

{
    id: 5,
    document_ids: [1, 2, 3]
}

I've been banging my head against the output marshaling syntax to no avail. Some of the things I've tried:

{'id': fields.Integer, 'document_ids':fields.List(fields.Integer, attribute='documents.id')}
{'id': fields.Integer, 'document_ids':fields.List(fields.Nested({'id':fields.Integer}), attribute='documents')}

What's the magic incantation?


Solution

  • The magic incantation is

    {'id': fields.Integer, 'name': fields.String, 'document-ids':{'id': fields.Integer}}
    

    It was right there in the "Complex Structures" paragraph in the documentation.