Reputation: 410
I'm trying to find a way to allow users to pass in a structured set of information as part of a POST to cloud endpoints in GAE using Python.
An example post would be as below. This is taken from the Google Tracks API but illustrates precisely what I'm trying to achieve
{
"entities": [
{
"name": "Ford Fiesta 001",
"type": "AUTOMOBILE"
},
{
"name": "Chevrolet Volt 001",
"type": "AUTOMOBILE"
},
{
"name": "Chevrolet Volt 002",
}
]
}
From reading of the Python cloud endpoints documentation it's not possible unless I potentially allow a free-form fragment of JSON to be sent in the request body which doesn't sound like a good idea - not that I've tried it yet.
Upvotes: 2
Views: 583
Reputation: 3591
This is quite simple to accomplish. You will need to make use of the repeated=True
value when constructing the messages.MessageField
in the messages.Message
-inheriting class which you define as the argument format for your endpoints function. Example code:
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
# represents a car with a name and a type
class Car(messages.Message):
name = messages.StringField(1)
type = messages.StringField(2)
# represents a collection of Cars
class MultiCars (messages.Message):
cars = messages.MessageField(Car, 1, repeated=True)
# class to return a simple string message
class ResponseMessage (messages.Message):
value = messages.StringField(1)
# api code
@endpoints.api(name='gmerrallApi',version='v1',
description='Example API for gmerrall')
class ExampleApi(remote.Service):
# endpoints method to insert a MultiCars
@endpoints.method(MultiCars,
ResponseMessage,
name='cars.insertMulti',
path='/insertMultiCars/{entities},
http_method='POST')
def insertMultiCars(self, request):
for car in request.entities:
print "got car (%s, %s)" % (car.name, car.type)
return ResponseMessage (value="The endpoints function ran to the end")
Take time to review this example and pay attention to the ways that the annotations and message classes interact with the endpoints code you write. The JSON format of the params that this API method receives will be exactly as your question used. The type info provided in the @endpoints.method
annotation tells the method how to interpret the JSON blob according to the message fields in those class definitions.
Upvotes: 2