How to I return JSON from a Google Cloud Function

Viewed 13506

How do I return JSON from a HTTP Google Cloud Function in Python? Right now I have something like:

import json

def my_function(request):
    data = ...
    return json.dumps(data)

This correctly returns JSON, but the Content-Type is wrong (it's text/html instead).

3 Answers

Cloud Functions has Flask available under the hood, so you can use it's jsonify function to return a JSON response.

In your function:

from flask import jsonify

def my_function(request):
    data = ...
    return jsonify(data)

This will return a flask.Response object with the application/json Content-Type and your data serialized to JSON.

You can also do this manually if you prefer to avoid using Flask:

import json

def my_function(request):
    data = ...
    return json.dumps(data), 200, {'Content-Type': 'application/json'}

You don't need Flask per se

import json

def my_function(request):
    data = ...
    return json.dumps(data), 200, {'ContentType': 'application/json'}

Make 200 whatever response code is suitable, eg. 404, 500, 301, etc.

If you're replying from a HTML AJAX request

return json.dumps({'success': True, 'data': data}), 200, {'ContentType': 'application/json'}

to return an error instead for the AJAX request

return json.dumps({'error': True}), 404, {'ContentType': 'application/json'}

For me, json.dumps() did not work in the cloud function. It worked only in my local server. So, I had to build the json by myself:

    headers= {
        'Access-Control-Allow-Origin': '*',
        'Content-Type':'application/json'
        }
    id1= "1234567"
    var1= "variable 1"
    text = '{"id1":"'+id1+'","var1":"'+var1+'"}'
    return (text, 200, headers)
Related