Serializing results

We need to return our results. The easiest way to do so is by defining the shape the JSON result should have through a serializer or marshalling model (https://flask-restplus.readthedocs.io/en/stable/marshalling.html).

A serializer model is defined as a dictionary with the expected fields and a field type:

from flask_restplus import fieldsmodel = {    'id': fields.Integer(),    'username': fields.String(),    'text': fields.String(),    'timestamp': fields.DateTime(),}thought_model = api_namespace.model('Thought', model)

The model will take a Python object, and convert each of the attributes into the corresponding JSON element, as defined in the field:

@api_namespace.route('/me/thoughts/')class MeThoughtListCreate(Resource): @api_namespace.marshal_with(thought_model) ...

Get Hands-On Docker for Microservices with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.