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).
To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.
In the general case, you can't. One reason is that a function usually needs the enclosing scope where it can find some of the variables it uses. In very specific cases you can use the Function constructor.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With