use `flask.jsonify()`

Python pattern

flask.jsonify() simplifies returning JSON from Flask routes by automatically serializing Python objects into JSON format and setting the appropriate Content-Type header, resulting in cleaner and more readable code while ensuring consistency and compatibility with web standards.

references


Apply with the Grit CLI
grit apply use_flask_jsonify

with json.dumps

BEFORE
import flask
import json
app = flask.Flask(__name__)

@app.route("/user")
def user():
    user_dict = get_user(request.args.get("id"))
    return json.dumps(user_dict)
AFTER
import flask
import json
from flask import jsonify

app = flask.Flask(__name__)

@app.route("/user")
def user():
    user_dict = get_user(request.args.get("id"))
    return jsonify(user_dict)

with dumps

BEFORE
from json import dumps

@app.route("/user")
def user():
    user_dict = get_user(request.args.get("id"))
    # ruleid:use-jsonify
    return dumps(user_dict)
AFTER
from json import dumps
from flask import jsonify

@app.route("/user")
def user():
    user_dict = get_user(request.args.get("id"))
    # ruleid:use-jsonify
    return jsonify(user_dict)

normal function

PYTHON
def dumps():
  pass
def test_empty_dumps():
    dumps()