14

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

5 Answers 5

28

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'}
Sign up to request clarification or add additional context in comments.

6 Comments

Python has a standard library to deal with json (json.dumps), no need of an external library to do this. In some cases, a simple str(data) do the trick.
@Oxydron I think you missed the last example I have here.
Indeed I missed :\, but I think that the only correct answer is that last one you written, because it solves the problem without external libraries.
I'd suggest adding the dash into 'Content-Type' for the second part of your answer.
@Oxydron since as Dustin points out, Flask is baked into gcloud functions, I'd argue this doesn't really add a dependency (eg request is a flask.Request object), it seems reasonable to make use of the available functionality. Adding flask to requests isn't actually needed for their example to work, though being explicit about your dependencies is reasonable.
|
3

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)

2 Comments

Did you import json? When you say it didn't work, what error did you get?
Yes, I imported and tried both json and flask.jsonify. It returned an error "INVALID ARGUMENT" but I was not able to get any information beyond this. I know it was on this line because if I remove it from the code, the error message does not appear.
2

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

Comments

0

Just tested this. Using the json module works well enough.

import json

def some_function(request):
    data = 'data_obj'
    return json.dumps(data)

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Hi Erick K, welcome to Stack Overflow. Thanks for the answer, and special double-thanks for having tested it before submitting — we are lucky to have you!
0

You need to specify a json string and the memetype so that it can be returned as a json. Here is an example.

@https_fn.on_request()
def on_request_get_profile(req: https_fn.Request) -> https_fn.Response:
    # Form dictionary
    response_dict = {"Name": "MyName", "Age": 30}
    json_response = json.dumps(response_dict)

    return https_fn.Response(json_response, mimetype='application/json')

That is all you really need but I will add more information here should ___.

You will probably be doing this in many places so I suggest you create a little helper function for this.

def form_response(data):
    return json.dumps(data)

Then whenever you need to return some data, you can use this helper function like so.

@https_fn.on_request()
def on_request_get_profile(req: https_fn.Request) -> https_fn.Response:
    # Perform your logic to produce the response.
    response = {"Name": "MyName", "Age": 30}
    return https_fn.Response(form_response(json_response ), mimetype='application/json')

Do note that it is not required to pass a python dictionary or json object to form_response method. Do you want to try a str or list object?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.