pythongoogle-app-enginegoogle-cloud-endpointsendpoints-proto-datastore

endpoints-proto-datastore: return different class then the input class


I want to have an endpoint which gets a certain type of object and returns a different type of object , instead of having them the same type.

for example:

class SomeClass(EndpointsModel):
    name = ndb.StringProperty()

class OtherClass(EndpointsModel):
    otherName = ndb.StringProperty()

@SomeClass.method(path='mymodel', http_method='POST', name='mymodel.insert')
def MyModelInsert(self, my_model):
    my_model.put()
    otherModel = OtherClass(otherName='someothername')
    return otherModel

currently i'm getting:

ServerError (Method MyApi.MyModelInsert expected response type <class '.SomeClass'>, sent <class '.OtherClass'>)

Is there any way to have the input Class different from the return Class ?


Solution

  • You can supply a response_message parameter in the method decorator, but that parameter has to be a ProtoRPC message class and not an EndpointsModel.

    You can get the message class from the EndpointsModel via the ProtoModel classmethod.

    And you have to return a ProtoRPC message and not an EndpointsModel from your method since the library doesn't do the conversation automatically for custom response classes. You can do this using the ToMessage method of the model.

    To summarize you would have this code (untested):

    @SomeClass.method(path='mymodel',
                      http_method='POST',
                      name='mymodel.insert'
                      response_message=OtherClass.ProtoModel())
    def MyModelInsert(self, my_model):
        my_model.put()
        otherModel = OtherClass(otherName='someothername')
        return otherModel.ToMessage()