Skip to content
Myr

add quickstart about JSON responses

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

authored by David Lord · committed by David Lord · parent 7bf8366 · Browse files · 1 file+34 added−1 removed
This commit

State

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

Diff stats

1 file+34 added−1 removed

  • other:+34 added−1 removed

1 file+34 added−1 removed

modified:docs/quickstart.rst+34 added-1 removed
681 unmodified lines
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.686return value is a dict, :func:`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 directly
28 unmodified lines
719 resp = make_response(render_template('error.html'), 404)720 resp.headers['X-Something'] = 'A value'721 return resp722723724APIs with JSON725``````````````726727A common response format when writing an API is JSON. It's easy to get728started writing such an API with Flask. If you return a ``dict`` from a729view, it will be converted to a JSON response.730731.. code-block:: python732733 @app.route("/me")734 def me_api():735 user = get_current_user()736 return {737 "username": user.username,738 "theme": user.theme,739 "image": url_for("user_image", filename=user.image),740 }741742Depending on your API design, you may want to create JSON responses for743types other than ``dict``. In that case, use the744:func:`~flask.json.jsonify` function, which will serialize any supported745JSON data type. Or look into Flask community extensions that support746more complex applications.747748.. code-block:: python749750 @app.route("/users")751 def users_api():752 users = get_all_users()753 return jsonify([user.to_json() for user in users])754755756.. _sessions:757758Sessions759--------
135 unmodified lines