Hướng dẫn json response flask python

I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?

@app.route("/summary")
def summary():
    d = make_summary()
    # send it back as json

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

asked Oct 26, 2012 at 5:56

0

As of Flask 1.1.0 a view can directly return a Python dict and Flask will call jsonify automatically.

@app.route("/summary")
def summary():
    d = make_summary()
    return d

If your Flask version is less than 1.1.0 or to return a different JSON-serializable object, import and use jsonify.

from flask import jsonify

@app.route("/summary")
def summary():
    d = make_summary()
    return jsonify(d)

answered Oct 26, 2012 at 15:33

Hướng dẫn json response flask python

codegeekcodegeek

30.7k11 gold badges62 silver badges61 bronze badges

0

jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )
    return response

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Nov 16, 2014 at 20:16

Hướng dẫn json response flask python

sclsscls

15.4k9 gold badges42 silver badges52 bronze badges

0

Pass keyword arguments to flask.jsonify and they will be output as a JSON object.

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id
    )
{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}

If you already have a dict, you can pass it directly as jsonify(d).

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Oct 26, 2012 at 6:11

Hướng dẫn json response flask python

zengrzengr

37.7k37 gold badges125 silver badges190 bronze badges

0

If you don't want to use jsonify for some reason, you can do what it does manually. Call flask.json.dumps to create JSON data, then return a response with the application/json content type.

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        mimetype='application/json'
    )
    return response

flask.json is distinct from the built-in json module. It will use the faster simplejson module if available, and enables various integrations with your Flask app.

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Jan 23, 2018 at 19:54

0

To return a JSON response and set a status code you can use make_response:

from flask import jsonify, make_response

@app.route('/summary')
def summary():
    d = make_summary()
    return make_response(jsonify(d), 200)

Inspiration taken from this comment in the Flask issue tracker.

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered May 22, 2019 at 22:02

roublerouble

14.8k16 gold badges101 silver badges97 bronze badges

If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files and pass it to the summary function.

from flask import request, jsonify
from werkzeug import secure_filename

@app.route('/summary', methods=['GET', 'POST'])
def summary():
    if request.method == 'POST':
        csv = request.files['data']
        return jsonify(
            summary=make_summary(csv),
            csv_name=secure_filename(csv.filename)
        )

    return render_template('submit_data.html')

Replace the 'data' key for request.files with the name of the file input in your HTML form.

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Dec 5, 2013 at 16:44

teechapteechap

7716 silver badges6 bronze badges

Flask 1.1.x supports returning a JSON dict without calling jsonify. If you want to return something besides a dict, you still need to call jsonify.

@app.route("/")
def index():
    return {
        "api_stuff": "values",
    }

is equivalent to

@app.route("/")
def index():
    return jsonify({
        "api_stuff": "values",
    })

See the pull request that added this: https://github.com/pallets/flask/pull/3111

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered May 14, 2020 at 8:32

sarfarazsajjadsarfarazsajjad

1,1072 gold badges16 silver badges30 bronze badges

0

I use a decorator to return the result of jsonfiy. I think it is more readable when a view has multiple returns. This does not support returning a tuple like content, status, but I handle returning error statuses with app.errorhandler instead.

import functools
from flask import jsonify

def return_json(f):
    @functools.wraps(f)
    def inner(**kwargs):
        return jsonify(f(**kwargs))

    return inner

@app.route('/test/')
@return_json
def test(arg):
    if arg == 'list':
        return [1, 2, 3]
    elif arg == 'dict':
        return {'a': 1, 'b': 2}
    elif arg == 'bool':
        return True
    return 'none of them'

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Jun 10, 2016 at 13:37

Hướng dẫn json response flask python

imaniman

20k8 gold badges30 silver badges31 bronze badges

0

Prior to Flask 0.11, jsonfiy would not allow returning an array directly. Instead, pass the list as a keyword argument.

@app.route('/get_records')
def get_records():
    results = [
        {
          "rec_create_date": "12 Jun 2016",
          "rec_dietary_info": "nothing",
          "rec_dob": "01 Apr 1988",
          "rec_first_name": "New",
          "rec_last_name": "Guy",
        },
        {
          "rec_create_date": "1 Apr 2016",
          "rec_dietary_info": "Nut allergy",
          "rec_dob": "01 Feb 1988",
          "rec_first_name": "Old",
          "rec_last_name": "Guy",
        },
    ]
    return jsonify(results=list)

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Jun 26, 2016 at 15:42

Hướng dẫn json response flask python

0

In Flask 1.1, if you return a dictionary and it will automatically be converted into JSON. So if make_summary() returns a dictionary, you can

from flask import Flask

app = Flask(__name__)

@app.route('/summary')
def summary():
    d = make_summary()
    return d

The SO that asks about including the status code was closed as a duplicate to this one. So to also answer that question, you can include the status code by returning a tuple of the form (dict, int). The dict is converted to JSON and the int will be the HTTP Status Code. Without any input, the Status is the default 200. So in the above example the code would be 200. In the example below it is changed to 201.

from flask import Flask

app = Flask(__name__)

@app.route('/summary')
def summary():
    d = make_summary()
    return d, 201  # 200 is the default

You can check the status code using

curl --request GET "http://127.0.0.1:5000/summary" -w "\ncode: %{http_code}\n\n"

answered Jan 3, 2020 at 14:37

Hướng dẫn json response flask python

Steven C. HowellSteven C. Howell

15.1k14 gold badges70 silver badges87 bronze badges

The answer is the same when using Flask's class-based views.

from flask import Flask, request, jsonify
from flask.views import MethodView

app = Flask(__name__)

class Summary(MethodView):
    def get(self):
        d = make_summary()
        return jsonify(d)

app.add_url_rule('/summary/', view_func=Summary.as_view('summary'))

Hướng dẫn json response flask python

davidism

113k24 gold badges367 silver badges323 bronze badges

answered Oct 24, 2019 at 11:40

if its a dict, flask can return it directly (Version 1.0.2)

def summary():
    d = make_summary()
    return d, 200

answered Dec 3, 2019 at 14:15

Hướng dẫn json response flask python

c8999c 3f964f64c8999c 3f964f64

1,2761 gold badge8 silver badges22 bronze badges

To serialize an object, use jsonify from flask module to jsonify the object, a dictionary gets serialized by default. Also, if you're dealing with files you can always use make_response.

answered Nov 12, 2021 at 10:49

bkoiki950bkoiki950

1871 silver badge3 bronze badges

1

I like this way:

    @app.route("/summary")
    def summary():
        responseBody = { "message": "bla bla bla", "summary": make_summary() }
        return make_response(jsonify(responseBody), 200)

answered Sep 16, 2020 at 13:58

Hướng dẫn json response flask python

Amin ShojaeiAmin Shojaei

4,3502 gold badges33 silver badges41 bronze badges

1

Not the answer you're looking for? Browse other questions tagged python json flask or ask your own question.