Skip to content
Myr

Allow dictionary return values as JSON

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This supports an increasingly common usecase whereby JSON is the primary response (rather than a templated string). Given Flask has a short syntax for HTML reponses, it seems fitting that it should also do so for JSON responses. In practice it allows, @app.route("/") def index(): return { "api_stuff": "values", }

authored by pgjones · committed by David Lord · parent 2616d97 · Browse files · 4 files+37 added−16 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+37 added−16 removed

  • tests:+10 added−2 removed
  • other:+27 added−14 removed

4 files+37 added−16 removed

modified:docs/quickstart.rst+17 added-14 removed
677 unmodified lines
678679About Responses680---------------681682The return value from a view function is automatically converted into a683response object for you. If the return value is a string it's converted684into a response object with the string as response body, a ``200 OK``685status code and a :mimetype:`text/html` mimetype.686The logic that Flask applies to converting return values into687response objects is as follows:682The return value from a view function is automatically converted into683a response object for you. If the return value is a string it's684converted into a response object with the string as response body, a685``200 OK`` status code and a :mimetype:`text/html` mimetype. If the686return value is a dict, ``jsonify`` is called to produce a response.687The logic that Flask applies to converting return values into response688objects is as follows:6896901. If a response object of the correct type is returned it's directly691 returned from the view.6912. If it's a string, a response object is created with that data and the692 default parameters.6933. If a tuple is returned the items in the tuple can provide extra information.694 Such tuples have to be in the form ``(response, status, headers)``,695 ``(response, headers)`` or ``(response, status)`` where at least one item696 has to be in the tuple. The ``status`` value will override the status code697 and ``headers`` can be a list or dictionary of additional header values.6984. If none of that works, Flask will assume the return value is a6922. If it's a string, a response object is created with that data and693 the default parameters.6943. If it's a dict, a response object is created using ``jsonify``.6954. If a tuple is returned the items in the tuple can provide extra696 information. Such tuples have to be in the form697 ``(response, status)``, ``(response, headers)``, or698 ``(response, status, headers)``. The ``status`` value will override699 the status code and ``headers`` can be a list or dictionary of700 additional header values.7015. If none of that works, Flask will assume the return value is a702 valid WSGI application and convert that into a response object.703704If you want to get hold of the resulting response object inside the view705you can use the :func:`~flask.make_response` function.
156 unmodified lines
modified:flask/app.py+6 added
42 unmodified lines
43 locked_cached_property,44 url_for,45 get_load_dotenv,46)47from .json import jsonify48from .logging import create_logger49from .sessions import SecureCookieSessionInterface50from .signals import (51 appcontext_tearing_down,
1949 unmodified lines
20012002 ``bytes`` (``str`` in Python 2)2003 A response object is created with the bytes as the body.20042005 ``dict``2006 A dictionary that will be jsonify'd before being returned.20072008 ``tuple``2009 Either ``(body, status, headers)``, ``(body, status)``, or2010 ``(body, headers)``, where ``body`` is any of the other types2011 allowed here, ``status`` is a string or an integer, and
55 unmodified lines
2067 # waiting to do it manually, so that the class can handle any2068 # special logic2069 rv = self.response_class(rv, status=status, headers=headers)2070 status = headers = None2071 elif isinstance(rv, dict):2072 rv = jsonify(rv)2073 else:2074 # evaluate a WSGI callable, or coerce a different response2075 # class to the correct type2076 try:
344 unmodified lines
modified:tests/test_basic.py+10 added-2 removed
1145 unmodified lines
1146 @app.route("/wsgi")1147 def from_wsgi():1148 return NotFound()11491150 assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1151 assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")1150 @app.route('/dict')1151 def from_dict():1152 return {"foo": "bar"}, 20111531154 assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1155 assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11561157 rv = client.get("/full_tuple")1158 assert rv.data == b"Meh"1159 assert rv.headers["X-Foo"] == "Testing"1160 assert rv.status_code == 400
23 unmodified lines
1184 rv = client.get("/wsgi")1185 assert b"Not Found" in rv.data1186 assert rv.status_code == 40411871188 rv = client.get('/dict')1189 assert rv.json == {"foo": "bar"}1190 assert rv.status_code == 201119111921193def test_response_type_errors():1194 app = flask.Flask(__name__)1195 app.testing = True1196
779 unmodified lines
modified:CHANGES.rst+4 added
50 unmodified lines
51 the Blinker library is not installed. :pr:`3208`52- Add an ``--extra-files`` option to the ``flask run`` CLI command to53 specify extra files that will trigger the reloader on change.54 :issue:`2897`55- Allow returning a dictionary from a view function. Similar to how56 returning a string will produce a ``text/html`` response, returning57 a dict will call ``jsonify`` to produce a ``application/json``58 response. :pr:`3111`5960.. _#2935: https://github.com/pallets/flask/issues/293561.. _#2957: https://github.com/pallets/flask/issues/295762.. _#2994: https://github.com/pallets/flask/pull/2994
947 unmodified lines