rizTaak
rizTaak

Reputation: 188

Return Datastore Entity from Cloud Endpoint in Python

Is there a way to return datastore entity by making it part of request/response message in cloud endpoint api implementation in python?

For example:

I have entity model defined as below

class District(ndb.Model):
    code = ndb.StringProperty(required=True)

Now I want to implement cloud api in python as

 @endpoints.method(request_message=DistrictMessage, response_message=DistrictMessage, name="DistrictApi.get_by_code")
def get_by_code(self, request):
#get code from District object in request message and 
#try to get entity based on it from datastore

where DistrictMessage is defined as

class DistrictMessage(messages.Message):    
    district = messages.MessageField(District, 1, required=False)

Above doesn't work as District is not a messages.Message but ndb.Model. We can do similar thing in GAE Java but I am not able to find it for python. Is it even possible? Or do I have to define a Message class for each Entity and do to/from mapping?

Thank you, rizTaak

Upvotes: 0

Views: 240

Answers (1)

Josh J
Josh J

Reputation: 6893

There is no way to do this directly. You can check out http://endpoints-proto-datastore.appspot.com/ for a supplemental library that lets you work with models instead of messages.

You will have to do something like this if you want to do it yourself.

class DistrictMessage(messages.Message):    
    code = messages.StringField(1, required=True)

class SomeApiClass():  # incomplete class def for syntax highlighting
    @endpoints.method(request_message=DistrictMessage, response_message=DistrictMessage, name="DistrictApi.get_by_code")
    def get_by_code(self, request):
        # get code from District object in request message and 
        # try to get entity based on it from datastore
        district = District.query(District.code == request.code).get()
        if district:
            # copy District properties to DistrictMessage kwargs
            # ndb.Model.to_dict() can be used here if you filter
            # out properties that aren't used in the DistrictMessage
            return DistrictMessage(code=district.code)
        raise endpoints.NotFoundException()

Upvotes: 1

Related Questions