Search code examples
pythongoogle-app-enginegoogle-cloud-platformgoogle-cloud-endpointsgoogle-cloud-endpoints-v2

Return JSON array as response using Google Cloud Endpoints Framework in Python


I am using Google Endpoints Framework with Python (https://cloud.google.com/endpoints/docs/frameworks/python/get-started-frameworks-python) and have been building REST APIs with it.

I am able to return JSON object (dictionaries) in the response like:

{
    "items":[
        {
            "id": "brand_1_id",
            "name": "Brand 1"
        },
        {
            "id": "brand_2_id",
            "name": "Brand 2"
        }
    ]
}

However, I am not able to return a JSON array (list) as response like:

[ { "id": "brand_1_id", "name": "Brand 1" }, { "id": "brand_2_id", "name": "Brand 2" } ]

Following are the code snippets I have been using to return the response

Following are the classes created to send a response:

class BrandResponse(messages.Message):
    id=messages.StringField(1, required=True)
    brandName = messages.StringField(2, required=True)
    brandEmail=messages.StringField(3, required=True)
    brandPhone=messages.StringField(4,required=True)
    brandAddress=messages.StringField(5,required=True)
    brandCity=messages.StringField(6,required=True)
    brandState=messages.StringField(7,required=True)
    brandCountry=messages.StringField(8,required=True)
    brandPostalCode=messages.StringField(9,required=True)

class MultipleBrandResponse(messages.Message):
    items=messages.MessageField(BrandResponse,1,repeated=True)

Following is the method that processes the request:

@endpoints.method(
        MULTIPLE_BRAND_PAGINATED_CONTAINER,
        MultipleBrandResponse,
        path='brand',
        http_method='GET',
        name='Get Brands',
        audiences=firebaseAudience
    )
    def getBrands(self,request):
        brandResponse=[]

        query = BrandDB.query()
        brands = query.fetch(request.limit, offset=request.start)
        for brand in brands:
            brandResponse.append(BrandResponse(
            id=brand.key.urlsafe(),
            brandName=brand.name,
            brandAddress=brand.address,
            brandCity=brand.city,
            brandState=brand.state,
            brandCountry=brand.country,
            brandPostalCode=brand.postalCode,
            brandPhone=brand.phone,
            brandEmail=brand.email))

        print("Brand count: "+str(brandResponse.count))

        if len(brandResponse) == 0:
            raise endpoints.NotFoundException("No brands")

        return MultipleBrandResponse(items=brandResponse)

Any idea how to return JSON array directly rather than wrapping in side a key inside a JSON object.


Solution

  • The framework is designed around returning Protocol Buffer messages, not JSON. It's possible you may have specified a message which that dict structure matches; hard to say without seeing your code.