Home > Backend Development > Python Tutorial > How Can I Return JSON Responses from Flask Views?

How Can I Return JSON Responses from Flask Views?

Barbara Streisand
Release: 2024-12-21 13:13:09
Original
265 people have browsed it

How Can I Return JSON Responses from Flask Views?

Returning JSON Responses from Flask Views

In Flask, views can conveniently return data in a JSON format, allowing seamless integration with front-end applications. Let's explore how this is achieved.

To return a JSON response, the view function can directly return a Python dictionary or list, and Flask will automatically convert it to JSON using its jsonify function. For example:

@app.route("/summary")
def summary():
    d = make_summary()
    return d
Copy after login

This approach is suitable for recent Flask versions. For older versions, or if you need more control over the JSON serialization process, you can import the jsonify function and use it explicitly:

from flask import jsonify

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

Using jsonify allows for custom JSON handling, such as specifying custom serializers or using JSONP. Here are some additional examples:

# Customizing JSON serialization
return jsonify({'foo': 'bar'}, {'_custom': lambda obj: obj.CustomFooSerializer() })

# JSONP response with callback parameter
return jsonify(foo='bar'), 200, {'jsonp':'myCallback'}
Copy after login

By returning JSON responses from Flask views, developers can easily create RESTful APIs or provide data in a consistent and consumable format for client applications.

The above is the detailed content of How Can I Return JSON Responses from Flask Views?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template