pythongoogle-cloud-platformgoogle-cloud-functions

How to I return JSON from a Google Cloud Function


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).


Solution

  • 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'}