Performance: HTTP status codes for APIs
This concept affects how quickly clients understand API responses and handle errors, impacting perceived responsiveness and user experience.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): # Returns 404 status code on error return jsonify({'error': 'Not found'}), 404
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): # Always returns 200 OK even on error return jsonify({'error': 'Not found', 'data': None}), 200
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Always 200 OK with error in body | N/A | N/A | N/A | [X] Bad |
| Correct HTTP status codes (e.g., 404, 500) | N/A | N/A | N/A | [OK] Good |
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/item/')
def get_item(id):
items = {1: 'apple', 2: 'banana'}
if id in items:
return jsonify({'item': items[id]}), 200
else:
return jsonify({'error': 'Item not found'}), 404/item/3?@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
if 'name' not in data:
return {'error': 'Name required'}, 400
return {'message': 'Added'}, 201Pass the test and this pattern moves unknown