Return JSON response from Flask view












338















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





























    338















    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



























      338












      338








      338


      78






      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
















      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






      python json flask






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 26 '17 at 16:45









      davidism

      65.8k12178191




      65.8k12178191










      asked Oct 26 '12 at 5:56









      Code NinjaCode Ninja

      1,83131111




      1,83131111
























          9 Answers
          9






          active

          oldest

          votes


















          555














          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


























          • As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

            – Wolfgang Kuehn
            Feb 21 at 16:24











          • Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

            – F. Malina
            Mar 13 at 15:31





















          154














          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








          • 8





            you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

            – naXa
            Apr 11 '16 at 20:46






          • 2





            or just return json.dumps(data), 200, 'application/json' is shorter

            – CpILL
            Aug 27 '18 at 9:33











          • For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

            – Patrick Mutuku
            Feb 15 at 14:59



















          101














          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



















          19














          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





          share|improve this answer


























          • import json (instead of from flask ...) works just as well.

            – Uri Goren
            Jan 11 at 18:03



















          15














          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

































            7














            You can write a decorator to convert the return value from a view function into a JSON response.



            def return_json(view):
            @functools.wraps(view)
            def wrapped_view(**values):
            return jsonify(view(**values))
            return wrapped_view


            @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





              @return_json doesn't work with status codes.

              – Roman Orac
              Sep 24 '18 at 9:11





















            4














            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)





            share|improve this answer

































              -2














              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

































                -2














                You can try this approach:



                from flask import jsonify, Flask

                app = Flask(__name__)

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





                share|improve this answer


























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13081532%2freturn-json-response-from-flask-view%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  9 Answers
                  9






                  active

                  oldest

                  votes








                  9 Answers
                  9






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  555














                  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


























                  • As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

                    – Wolfgang Kuehn
                    Feb 21 at 16:24











                  • Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

                    – F. Malina
                    Mar 13 at 15:31


















                  555














                  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


























                  • As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

                    – Wolfgang Kuehn
                    Feb 21 at 16:24











                  • Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

                    – F. Malina
                    Mar 13 at 15:31
















                  555












                  555








                  555







                  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















                  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














                  share|improve this answer



                  share|improve this answer








                  edited Jan 26 '17 at 16:41









                  davidism

                  65.8k12178191




                  65.8k12178191










                  answered Oct 26 '12 at 15:33









                  codegeekcodegeek

                  18.6k84859




                  18.6k84859













                  • As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

                    – Wolfgang Kuehn
                    Feb 21 at 16:24











                  • Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

                    – F. Malina
                    Mar 13 at 15:31





















                  • As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

                    – Wolfgang Kuehn
                    Feb 21 at 16:24











                  • Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

                    – F. Malina
                    Mar 13 at 15:31



















                  As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

                  – Wolfgang Kuehn
                  Feb 21 at 16:24





                  As of flask version 1.0.2, jsonify will not preserve the attribute order of a passed dict. If you need that, use the Response class, see other answers.

                  – Wolfgang Kuehn
                  Feb 21 at 16:24













                  Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

                  – F. Malina
                  Mar 13 at 15:31







                  Why is the browser output an ugly string? app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True, does nothing

                  – F. Malina
                  Mar 13 at 15:31















                  154














                  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








                  • 8





                    you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

                    – naXa
                    Apr 11 '16 at 20:46






                  • 2





                    or just return json.dumps(data), 200, 'application/json' is shorter

                    – CpILL
                    Aug 27 '18 at 9:33











                  • For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

                    – Patrick Mutuku
                    Feb 15 at 14:59
















                  154














                  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








                  • 8





                    you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

                    – naXa
                    Apr 11 '16 at 20:46






                  • 2





                    or just return json.dumps(data), 200, 'application/json' is shorter

                    – CpILL
                    Aug 27 '18 at 9:33











                  • For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

                    – Patrick Mutuku
                    Feb 15 at 14:59














                  154












                  154








                  154







                  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















                  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














                  share|improve this answer



                  share|improve this answer








                  edited Jan 26 '17 at 16:51









                  davidism

                  65.8k12178191




                  65.8k12178191










                  answered Nov 16 '14 at 20:16









                  sclsscls

                  6,53862839




                  6,53862839













                  • @Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…

                    – rob
                    Jun 16 '15 at 0:41








                  • 8





                    you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

                    – naXa
                    Apr 11 '16 at 20:46






                  • 2





                    or just return json.dumps(data), 200, 'application/json' is shorter

                    – CpILL
                    Aug 27 '18 at 9:33











                  • For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

                    – Patrick Mutuku
                    Feb 15 at 14:59



















                  • @Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…

                    – rob
                    Jun 16 '15 at 0:41








                  • 8





                    you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

                    – naXa
                    Apr 11 '16 at 20:46






                  • 2





                    or just return json.dumps(data), 200, 'application/json' is shorter

                    – CpILL
                    Aug 27 '18 at 9:33











                  • For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

                    – Patrick Mutuku
                    Feb 15 at 14:59

















                  @Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…

                  – rob
                  Jun 16 '15 at 0:41







                  @Tjorriemorrie Might not want a top level list. See stackoverflow.com/questions/3503102/…

                  – rob
                  Jun 16 '15 at 0:41






                  8




                  8





                  you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

                  – naXa
                  Apr 11 '16 at 20:46





                  you can return status code with jsonify too return jsonify({"Error" : "Access restricted"}), 403

                  – naXa
                  Apr 11 '16 at 20:46




                  2




                  2





                  or just return json.dumps(data), 200, 'application/json' is shorter

                  – CpILL
                  Aug 27 '18 at 9:33





                  or just return json.dumps(data), 200, 'application/json' is shorter

                  – CpILL
                  Aug 27 '18 at 9:33













                  For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

                  – Patrick Mutuku
                  Feb 15 at 14:59





                  For some use cases, you can use jsonify(data) in place of json.dumps(data) and it will work fine.

                  – Patrick Mutuku
                  Feb 15 at 14:59











                  101














                  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
















                  101














                  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














                  101












                  101








                  101







                  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















                  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














                  share|improve this answer



                  share|improve this answer








                  edited Jan 26 '17 at 20:30









                  davidism

                  65.8k12178191




                  65.8k12178191










                  answered Oct 26 '12 at 6:11









                  zengrzengr

                  26.4k32110179




                  26.4k32110179













                  • 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



















                  • 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

















                  can you please elaborate me with the code to identify filename.

                  – Code Ninja
                  Oct 26 '12 at 8:23





                  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





                  @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




                  1





                  What if I want to return structure like { 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98} ?

                  – David Sergey
                  Nov 13 '13 at 15:39







                  What if I want to return structure like { 'names': { 'first': 'Frank', last: 'Sinatra'}, 'age': 98} ?

                  – David Sergey
                  Nov 13 '13 at 15:39






                  3




                  3





                  It's just a nested dict. Try this: jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})

                  – zengr
                  Nov 13 '13 at 16:06





                  It's just a nested dict. Try this: jsonify({ 'names': { 'first': 'Frank', 'last': 'Sinatra'}, 'age': 98})

                  – zengr
                  Nov 13 '13 at 16:06











                  19














                  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





                  share|improve this answer


























                  • import json (instead of from flask ...) works just as well.

                    – Uri Goren
                    Jan 11 at 18:03
















                  19














                  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





                  share|improve this answer


























                  • import json (instead of from flask ...) works just as well.

                    – Uri Goren
                    Jan 11 at 18:03














                  19












                  19








                  19







                  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





                  share|improve this answer















                  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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 25 '18 at 23:15









                  davidism

                  65.8k12178191




                  65.8k12178191










                  answered Jan 23 '18 at 19:54









                  Anthony AwuleyAnthony Awuley

                  64469




                  64469













                  • import json (instead of from flask ...) works just as well.

                    – Uri Goren
                    Jan 11 at 18:03



















                  • import json (instead of from flask ...) works just as well.

                    – Uri Goren
                    Jan 11 at 18:03

















                  import json (instead of from flask ...) works just as well.

                  – Uri Goren
                  Jan 11 at 18:03





                  import json (instead of from flask ...) works just as well.

                  – Uri Goren
                  Jan 11 at 18:03











                  15














                  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






























                    15














                    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




























                      15












                      15








                      15







                      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















                      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














                      share|improve this answer



                      share|improve this answer








                      edited Jan 26 '17 at 16:58









                      davidism

                      65.8k12178191




                      65.8k12178191










                      answered Dec 5 '13 at 16:44









                      teechapteechap

                      54656




                      54656























                          7














                          You can write a decorator to convert the return value from a view function into a JSON response.



                          def return_json(view):
                          @functools.wraps(view)
                          def wrapped_view(**values):
                          return jsonify(view(**values))
                          return wrapped_view


                          @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





                            @return_json doesn't work with status codes.

                            – Roman Orac
                            Sep 24 '18 at 9:11


















                          7














                          You can write a decorator to convert the return value from a view function into a JSON response.



                          def return_json(view):
                          @functools.wraps(view)
                          def wrapped_view(**values):
                          return jsonify(view(**values))
                          return wrapped_view


                          @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





                            @return_json doesn't work with status codes.

                            – Roman Orac
                            Sep 24 '18 at 9:11
















                          7












                          7








                          7







                          You can write a decorator to convert the return value from a view function into a JSON response.



                          def return_json(view):
                          @functools.wraps(view)
                          def wrapped_view(**values):
                          return jsonify(view(**values))
                          return wrapped_view


                          @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















                          You can write a decorator to convert the return value from a view function into a JSON response.



                          def return_json(view):
                          @functools.wraps(view)
                          def wrapped_view(**values):
                          return jsonify(view(**values))
                          return wrapped_view


                          @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














                          share|improve this answer



                          share|improve this answer








                          edited Jul 25 '18 at 23:13









                          davidism

                          65.8k12178191




                          65.8k12178191










                          answered Jun 10 '16 at 13:37









                          imaniman

                          9,22162421




                          9,22162421








                          • 1





                            @return_json doesn't work with status codes.

                            – Roman Orac
                            Sep 24 '18 at 9:11
















                          • 1





                            @return_json doesn't work with status codes.

                            – Roman Orac
                            Sep 24 '18 at 9:11










                          1




                          1





                          @return_json doesn't work with status codes.

                          – Roman Orac
                          Sep 24 '18 at 9:11







                          @return_json doesn't work with status codes.

                          – Roman Orac
                          Sep 24 '18 at 9:11













                          4














                          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)





                          share|improve this answer






























                            4














                            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)





                            share|improve this answer




























                              4












                              4








                              4







                              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)





                              share|improve this answer















                              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)






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jul 25 '18 at 23:10









                              davidism

                              65.8k12178191




                              65.8k12178191










                              answered Jun 26 '16 at 15:42









                              mania_devicemania_device

                              11517




                              11517























                                  -2














                                  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






























                                    -2














                                    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




























                                      -2












                                      -2








                                      -2







                                      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















                                      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














                                      share|improve this answer



                                      share|improve this answer








                                      edited May 3 '16 at 16:56

























                                      answered Jul 28 '15 at 19:05









                                      Papouche GuinslyzinhoPapouche Guinslyzinho

                                      2,40742753




                                      2,40742753























                                          -2














                                          You can try this approach:



                                          from flask import jsonify, Flask

                                          app = Flask(__name__)

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





                                          share|improve this answer






























                                            -2














                                            You can try this approach:



                                            from flask import jsonify, Flask

                                            app = Flask(__name__)

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





                                            share|improve this answer




























                                              -2












                                              -2








                                              -2







                                              You can try this approach:



                                              from flask import jsonify, Flask

                                              app = Flask(__name__)

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





                                              share|improve this answer















                                              You can try this approach:



                                              from flask import jsonify, Flask

                                              app = Flask(__name__)

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






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jan 21 at 10:32









                                              iamdanchiv

                                              2,67642432




                                              2,67642432










                                              answered Jan 21 at 9:49









                                              theophilus okoyetheophilus okoye

                                              1




                                              1






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13081532%2freturn-json-response-from-flask-view%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  MongoDB - Not Authorized To Execute Command

                                                  How to fix TextFormField cause rebuild widget in Flutter

                                                  Npm cannot find a required file even through it is in the searched directory