Search code examples
pythonjsonpython-2.7nullflask-restful

Flask-RESTful - don't return object property instead of returning null


Let's say I've got a clients table with id, name and email fields. An email field is optional.

The code looks like this:

client_fields = {
   'id' : fields.String,
   'name' : fields.String,
   'email' : fields.String
}

And for displaying:

class ClientList(Resource):
    @marshal_with(client_fields)
    def get(self):
       return model.Client.query.all()

When email is not provided, API returns JSON like this:

{
   "id": "1",
   "name": "John Doe",
   "email": null
}

But instead I want it to return this object:

{
   "id": "1",
   "name": "John Doe"
}

Which basically means that instead of a property with null value I want it to return no such property at all. Is there a way to achieve that?


Solution

  • I would use the marshal function instead of the marshal_with decorator:

    class ClientList(Resource):
        def get(self):
           clients = []
           for client in model.Client.query.all():
               if client.email:
                   clients.append(marshal(client_fields))
               else:
                   clients.append(marshal(client_fields_no_email))
           return clients
    

    Or even better

    class ClientList(Resource):
        def get(self):
           return [client_marshal(client) for client in model.Client.query.all()]
    

    with

    def client_marshal(client):
        if client.email:
            return {'id' : fields.String,
                    'name' : fields.String,
                    'email' : fields.String}
        else:
            return {'id' : fields.String,
                    'name' : fields.String}