In web development, especially in front-end and back-end separated architectures, APIs (Application Programming Interfaces) are the core of data exchange. As a lightweight Python web framework, Flask is often used for rapid API development due to its simplicity. This article will focus on how to return JSON-formatted data in Flask and correctly set HTTP status codes, helping beginners understand the basic points of API development.
1. Why Return JSON?¶
When developing APIs, structured data needs to be exchanged between the front and back ends. JSON (JavaScript Object Notation) is the most commonly used data format, as it is lightweight, easy to parse, and compatible with most programming languages. For example, the front end can easily convert JSON data into JavaScript objects, and the back end can process data through JSON parsers.
2. Returning JSON Data in Flask¶
Flask provides a dedicated tool to handle JSON data—the jsonify function. It not only converts Python dictionaries/lists into JSON format but also automatically sets the response header Content-Type: application/json, ensuring the front end correctly identifies the data type.
2.1 Basic Usage Example¶
First, install Flask (if not already installed):
pip install flask
Create a simple Flask application to return JSON data:
from flask import Flask, jsonify
app = Flask(__name__)
# Define a route to return JSON data
@app.route('/greet')
def greet():
# Construct a Python dictionary (key-value pairs)
response_data = {
"message": "Hello, Flask API!",
"status": "success",
"code": 200
}
# Use jsonify to return JSON
return jsonify(response_data)
Run and Test: Start the Flask application and visit http://localhost:5000/greet. You will see a JSON response like this:
{
"message": "Hello, Flask API!",
"status": "success",
"code": 200
}
2.2 Common Pitfall: Directly Returning a Dictionary¶
Question: If you directly return a Python dictionary (instead of using jsonify), will Flask automatically convert it to JSON?
Answer: It can work, but it is not recommended. For example:
@app.route('/test')
def test():
data = {"name": "Alice", "age": 20}
return data # Flask may automatically convert to JSON, but this depends on the version/scenario
While this method works in most cases, jsonify is more explicit and can handle non-dictionary types (e.g., lists, tuples). Thus, it is always better to use jsonify.
3. Role of HTTP Status Codes¶
HTTP status codes are “result reports” returned by the server to the client, helping the front end (or caller) determine if the request was successful. Examples include:
- 200 OK: Request successful (most common);
- 201 Created: Resource created successfully (often used for POST requests);
- 400 Bad Request: Request parameter error;
- 404 Not Found: Resource does not exist;
- 500 Internal Server Error: Server internal error.
4. Setting HTTP Status Codes in Flask¶
Flask supports two methods to set status codes: returning a tuple or using make_response to construct a response object.
4.1 Returning a Tuple (Data + Status Code)¶
In view functions, directly return a tuple (response_data, status_code). For example:
@app.route('/user/<int:user_id>')
def get_user(user_id):
# Simulate data retrieval (e.g., from a database)
user = {"id": user_id, "name": "Bob"}
# Return JSON data + status code 200 (success)
return jsonify(user), 200
@app.route('/user/<int:user_id>')
def get_user(user_id):
if user_id == 0:
# Return error message + status code 404 (resource not found)
return jsonify({"error": "User not found"}), 404
user = {"id": user_id, "name": "Bob"}
return jsonify(user), 200
4.2 Using make_response for Custom Responses¶
For scenarios requiring more complex settings (e.g., custom response headers), first create a response object with make_response, then set the status code:
from flask import make_response
@app.route('/login')
def login():
# Simulate login failure
response = jsonify({"error": "Invalid password"})
response.status_code = 401 # Set status code to "Unauthorized"
return response
5. Examples of Common Scenarios¶
Here are the most common API development scenarios with corresponding JSON returns and status code settings:
Scenario 1: Successful Data Return (GET Request)¶
Requirement: Get a product list
Code:
from flask import Flask, jsonify
app = Flask(__name__)
# Simulate product data
products = [
{"id": 1, "name": "Laptop", "price": 999},
{"id": 2, "name": "Phone", "price": 499}
]
@app.route('/products', methods=['GET'])
def get_products():
return jsonify({
"status": "success",
"data": products
}), 200 # 200 OK (default status code, can be omitted)
Scenario 2: Successful Resource Creation (POST Request)¶
Requirement: Create a new user
Code:
from flask import Flask, jsonify, request # Import request to handle request data
app = Flask(__name__)
users = {} # Simulate a database
@app.route('/users', methods=['POST'])
def create_user():
# Get JSON data submitted by the front end
new_user = request.get_json()
if not new_user or 'name' not in new_user:
# Parameter error, return 400
return jsonify({"error": "Name is required"}), 400
user_id = len(users) + 1
users[user_id] = new_user
# Return newly created user data + status code 201 (Created)
return jsonify({
"status": "success",
"data": users[user_id],
"user_id": user_id
}), 201
Scenario 3: Resource Not Found (404 Error)¶
Requirement: Query a non-existent user
Code:
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
if user_id not in users:
# Resource not found, return 404
return jsonify({"error": f"User {user_id} not found"}), 404
return jsonify(users[user_id]), 200
Scenario 4: Server Internal Error (500 Error)¶
Requirement: Simulate a server exception
Code:
@app.route('/error')
def trigger_error():
try:
# Intentionally cause an error (e.g., division by zero)
1 / 0
except:
# Return error message + status code 500
return jsonify({"error": "Server internal error"}), 500
6. Summary¶
- Returning JSON: Always use the
jsonifyfunction to ensure correct data format and front-end compatibility. - Status Code Setting: Use tuples
(jsonify(data), status_code)ormake_responseto clearly indicate request results (success/failure). - Common Status Codes:
200(success),201(created),400(parameter error),404(resource not found),500(server error).
With these fundamentals, you can develop standardized and clear Flask APIs to enable smooth front-end and back-end data interaction.