Performance: JSON request parsing
This affects server response time and user experience by how quickly the server reads and processes incoming JSON data.
from flask import request def endpoint(): parsed = request.get_json() # process parsed data return 'OK'
from flask import request def endpoint(): data = request.data import json parsed = json.loads(data) # process parsed data return 'OK'
| Pattern | CPU Parsing Time | Error Handling | Blocking Time | Verdict |
|---|---|---|---|---|
| Manual json.loads(request.data) | High | Manual, error-prone | Blocks longer | [X] Bad |
| Flask request.get_json() | Low | Built-in, safe | Minimal blocking | [OK] Good |
request object provides methods to access incoming request data.get_json() is designed to parse JSON data from the request body safely.request from flask and calls request.get_json() as a method.request.get_json() with parentheses to parse JSON.from flask import Flask, request
app = Flask(__name__)
@app.route('/user', methods=['POST'])
def user():
data = request.get_json()
return f"Hello, {data['name']}!"
request.get_json() parses it into a Python dict.data['name'] which exists, so it returns the formatted string "Hello, Alice!".@app.route('/submit', methods=['POST'])
def submit():
data = request.get_json()
return data['email']
data['email'] without checking if 'email' exists in the JSON data.@app.route('/info', methods=['POST'])
def info():
data = request.get_json()
return data['id']
request.get_json(silent=True) returns None instead of raising an error if JSON is missing or invalid.data['id'], check if data is not None to avoid crashes.Pass the test and this pattern moves unknown