Search code examples
google-app-enginegoogle-cloud-datastoregoogle-cloud-endpointsapp-engine-ndbendpoints-proto-datastore

How to upload an image through appengine endpoints api?


I am using Endpoints Proto Datastore API. Suppose I have code like this :

Model :

class MyModel(EndpointsModel):
  _message_fields_schema = ('name', 'image')
  name = ndb.StringProperty()
  image = ndb.BlobProperty()

API :

@endpoints.api(name='myapi', version='v1', description='my api')
class MyApi(remote.Service):

@MyModel.method(name='mymodel.insert', path='mymodel')
def insert_mymodel(self, data):
    data.put()
    return data

How can I upload image to the datastore through api? Thank you in advance.


Solution

  • Haven't done it myself but taken from here. You need to use the bytes type and encode the image into base64:

    When using Cloud Endpoints, the bytes sent to a BytesField must be base64 encoded.

    After being sent and validated through Google's API infrastructure, the base64 encoded bytes will be sent along to your protorpc.remote.Service class and converted from a base64 string to a native byte-string (instance of str) in Python.

    So you'll need your clients to take the image bytes and convert them to base64.

    To encode a byte string as base64 in Javascript, see How can you encode to Base64 using Javascript?, to do the same in Python, simply call

    import base64 base64.b64encode(byte_string)