Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 378
zorza Avatar asked Mar 20 '15 10:03

zorza


1 Answers

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}
like image 154
DaveBensonPhillips Avatar answered Oct 01 '22 14:10

DaveBensonPhillips