Consider this Flask route that expects JSON data with a 'name' key:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello():
data = request.get_json(force=True)
if 'name' not in data:
return jsonify({'error': 'Missing name'}), 400
return jsonify({'message': f"Hello, {data['name']}!"})What happens if the client sends a POST request with invalid JSON body?
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/hello', methods=['POST']) def hello(): data = request.get_json(force=True) if 'name' not in data: return jsonify({'error': 'Missing name'}), 400 return jsonify({'message': f"Hello, {data['name']}!"})
Think about what happens when force=True is used and the JSON is invalid.
Using request.get_json(force=True) forces Flask to parse the body as JSON even if the content type is wrong. If the JSON is invalid, Flask raises a BadRequest exception, which results in a 400 Bad Request error if not handled.
Given this Flask route using request.get_json() and manual validation:
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
if not data or 'username' not in data or 'password' not in data:
return {'error': 'Missing fields'}, 422
return {'status': 'success', 'user': data['username']}What response does the server send if the client sends {"username": "alice"} JSON?
@app.route('/register', methods=['POST']) def register(): data = request.get_json() if not data or 'username' not in data or 'password' not in data: return {'error': 'Missing fields'}, 422 return {'status': 'success', 'user': data['username']}
Check if all required keys are present in the JSON data.
The route checks if password is missing and returns a 422 error with a message. Since the client sent only username, the response is 422 with the error JSON.
Given a Marshmallow schema UserSchema to validate incoming JSON, which Flask route code correctly validates and returns errors if invalid?
from flask import Flask, request, jsonify from marshmallow import Schema, fields, ValidationError app = Flask(__name__) class UserSchema(Schema): username = fields.Str(required=True) age = fields.Int(required=True) @app.route('/user', methods=['POST']) def create_user(): # Validation code here pass
Remember that load validates and deserializes, and raises ValidationError on failure.
Option C correctly uses schema.load() inside a try-except block to catch validation errors and return them with a 400 status. Other options misuse validate or dump or omit error handling.
Examine this Flask route:
@app.route('/data', methods=['POST'])
def data():
data = request.get_json(force=True)
if not data:
return {'error': 'No data'}, 400
return {'received': data}Clients send valid JSON but always get 400 with 'No data'. Why?
@app.route('/data', methods=['POST']) def data(): data = request.get_json(force=True) if not data: return {'error': 'No data'}, 400 return {'received': data}
Think about how Python treats empty dictionaries in boolean contexts.
An empty dictionary {} is falsy in Python, so if not data is true and returns 400. The client likely sends an empty JSON object, which is valid but triggers the error.
Choose the best practice for validating incoming JSON requests in Flask applications.
Consider maintainability and clear error handling in your choice.
Using a validation library like Marshmallow allows clear schema definitions, automatic validation, and consistent error messages. Manual checks or forcing JSON parsing can lead to errors or messy code.