Katedral Pillon
Katedral Pillon

Reputation: 14864

Google cloud endpoint RequestMessage with multiple fields resolution

Cloud endpoint ResponseMessage seem straightforward to me. If I have a response message class

class FoodieResponseMessage(messages.Message):
  name = messages.StringField(1)
  fav_food = messages.StringField(2)
  city = messages.StringField(3)

invoking it is as simple as

FoodieResponseMessage(name="A", fav_food="B", city="C")

But what of a RequestMessage with multiple fields? All I get from the service endpoint method is a request object. How do I know what field goes where?

class FoodieRequestMessage(messages.Message):
  name = messages.StringField(1)
  id = messages.StringField(2)
  sitting_table = messages.StringField(3)

 @endpoints.method(FoodieRequestMessage, FoodieResponseMessage)
 def process(self, request):
   name = request.name
   id = request.id
   table = request.sitting_table

How does the request match the field so that i don't end up getting a user's sitting_table when I do request.name?

Upvotes: 0

Views: 410

Answers (1)

bossylobster
bossylobster

Reputation: 10163

Your methods need to be members of an API class:

from protorpc import remote

class FoodieAPI(remote.Service):

  @endpoints.method(FoodieRequestMessage, FoodieResponseMessage)
  def process(self, request):
    # Handle request

Since process is a member of a remote.Service subclass, the actual handler which is created by

application = endpoints.api_server([FoodieApi])

knows how to turn JSON into the native message request class you have specified (FoodieRequestMessage) and also expects you to return an instance of the response class you have specified (FoodieResponseMessage) because it can convert that back to JSON as well.

For example:

>>> import json
>>> from protorpc import protojson
>>>
>>> payload = json.dumps({
>>>     'name': 'Dan', 
>>>     'fav_food': 'Mac and Cheese', 
>>>     'city': 'San Francisco'
>>> })
>>> message = protojson.decode_message(FoodieResponseMessage, payload)
>>> message
<FoodieResponseMessage
 name: u'Dan'
 fav_food: u'Mac and Cheese'
 city: u'San Francisco'>

so when your request payload is

{"city": "San Francisco", "fav_food": "Mac and Cheese", "name": "Dan"}

the request object in your method will have

>>> message.name
u'Dan'
>>> message.fav_food
u'Mac and Cheese'
>>> message.city
u'San Francisco'

Upvotes: 2

Related Questions