`` with the HTML returned by a request.
.. code-block:: html
{{ include "geology_fact.html" }}
Return JSON from Views
----------------------
To return a JSON object from your API view, you can directly return a
dict from the view. It will be serialized to JSON automatically.
.. code-block:: python
@app.route("/user/
")
def user_detail(id):
user = User.query.get_or_404(id)
return {
"username": User.username,
"email": User.email,
"picture": url_for("static", filename=f"users/{id}/profile.png"),
}
If you want to return another JSON type, use the
:func:`~flask.json.jsonify` function, which creates a response object
with the given data serialized to JSON.
.. code-block:: python
from flask import jsonify
@app.route("/users")
def user_list():
users = User.query.order_by(User.name).all()
return jsonify([u.to_json() for u in users])
It is usually not a good idea to return file data in a JSON response.
JSON cannot represent binary data directly, so it must be base64
encoded, which can be slow, takes more bandwidth to send, and is not as
easy to cache. Instead, serve files using one view, and generate a URL
to the desired file to include in the JSON. Then the client can make a
separate request to get the linked resource after getting the JSON.
Receiving JSON in Views
-----------------------
Use the :attr:`~flask.Request.json` property of the
:data:`~flask.request` object to decode the request's body as JSON. If
the body is not valid JSON, or the ``Content-Type`` header is not set to
``application/json``, a 400 Bad Request error will be raised.
.. code-block:: python
from flask import request
@app.post("/user/")
def user_update(id):
user = User.query.get_or_404(id)
user.update_from_json(request.json)
db.session.commit()
return user.to_json()