Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 934
Dustin Ingram Avatar asked Nov 12 '18 23:11

Dustin Ingram


People also ask

How do I return a JSON response?

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.

Can you use functions in JSON?

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.


1 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'}
like image 98
Dustin Ingram Avatar answered Sep 19 '22 17:09

Dustin Ingram