![]() |
VOOZH | about |
When developing APIs with Flask, you will often need to send JSON responses. Although both jsonify() and json.dumps() can be used for this, Flask provides the jsonify() helper function for a more seamless experience.
jsonify() is a built-in Flask function that converts Python dictionaries and objects into JSON response objects. It also automatically sets:
This makes jsonify() more convenient than manually using json.dumps() with Response.
jsonify(*args, **kwargs)
Let's look at some of the examples and use cases for jsonify().
You can use jsonify() without any arguments, in this case it will return an empty JSON response object with a default status code of 200 (OK) and a default content type of application/json.
Output:
{}
Explanation:
In this example, we are calling jsonify() with a single positional argument (the list of user objects), as well as two keyword arguments with status and mimetype.
Output:
{
"users": [
{"id": 1, "username": "Alice"},
{"id": 2, "username": "Bob"}
]
}
Explanation:
In this example, we have a Flask app with a route that returns a list of user objects. When a client makes a request to this route, the get_users() function is executed and the list of user objects is converted to a JSON response object using the jsonify() function. This JSON response object is then sent back to the client.
Output:
Explanation:
In contrast, if you were to use the json.dumps() function, you would need to convert the list of user objects to a JSON-formatted string yourself, and then set the appropriate response headers and return the response to the client manually:
Using jsonify() is generally easier and more convenient than using json.dumps(), so it's recommended to use jsonify() whenever possible in Flask apps.
Visit URL: http://127.0.0.1:5000/api/users
There are several reasons why it is recommended to use the jsonify() function instead of the json.dumps() function in Flask apps:
Related Articles: