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
share|improve this question
up vote 250 down vote accepted

Pass the summary data to the jsonify function, which returns a JSON response.

from flask import jsonify

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

As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.

share|improve this answer

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
share|improve this answer
    
@Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/… – rob Jun 16 '15 at 0:41
    
you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403 – naXa Apr 11 '16 at 20:46

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
}
share|improve this answer
    
can you please elaborate me with the code to identify filename. – Code Ninja Oct 26 '12 at 8:23
    
@CodeNinja What do you mean? If you want to putput the f dict from your original code, you should do return jsonify(**f). – Markus Unterwaditzer Oct 30 '12 at 6:59
1  
What if I want to return structure like { 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98} ? – David Sergey Nov 13 '13 at 15:39
3  
It's just a nested dict. Try this: jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98}) – zengr Nov 13 '13 at 16:06

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.

share|improve this answer

Although flask.jsonify is easy to use but I prefer to use a decorator to return json. It helps to returns any json type and is more readable when you have multiple returns in your method. (note that this sample works for 200 responses, I return errors with raising exceptions and Flask.errorhandler)

def return_json(f):
    @functools.wraps(f)
    def inner(*a, **k):
        return json.dumps(f(*a, **k))
    return inner


@app.route('/test/<arg>')
@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 'non of them'
share|improve this answer
1  
Not sure but this will return a wrong mimetype ('html/text' instead of 'application/json') – gdoumenc Jan 26 at 14:40

Although an old question, I thought I'll add this if anyone is looking to return an array of JSONs. Flask 0.10 allows you to do this and it's pretty straightforward.

@app.route('/get_records')
def get_records():
    list = [
        {
          "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)
share|improve this answer
1  
This is no different than the existing answers. – davidism Jan 26 at 17:12
    
not sure what part of "if anyone is looking to return an array of JSONs" was not clear there. – Mohammed Anees Jun 21 at 11:15
1  
jsonify works with any type, returning a list doesn't warrant a new answer. I didn't say it was unclear, I said it wasn't a unique answer. – davidism Jun 21 at 12:54
    
Ah, okay. it was not very apparent, when I was looking for the solution - so I thought it would be helpful to someone. Thanks for clarifying. – Mohammed Anees Jun 21 at 13:20

Like said previously jsonify is the best way or you could also use Flask-responses' package at https://github.com/Parkayun/flask-responses

@app.route("/json")
def hello():
    return json_response(your_dict, status_code=201)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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