0
0
Flaskframework~20 mins

Request validation in Flask - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Request Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when sending invalid JSON to this Flask route?

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?

Flask
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']}!"})
AThe server raises a 400 Bad Request error due to JSON decoding failure.
BThe server returns a 200 OK with message 'Hello, None!' because data is None.
CThe server returns a 200 OK with an empty JSON object.
DThe server returns a 400 Bad Request error with a JSON error message about invalid JSON.
Attempts:
2 left
💡 Hint

Think about what happens when force=True is used and the JSON is invalid.

state_output
intermediate
2:00remaining
What is the response when required fields are missing in validated request data?

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?

Flask
@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']}
AHTTP 200 with JSON {'status': 'success', 'user': 'alice'}
BHTTP 500 Internal Server Error
CHTTP 400 with empty response body
DHTTP 422 with JSON {'error': 'Missing fields'}
Attempts:
2 left
💡 Hint

Check if all required keys are present in the JSON data.

📝 Syntax
advanced
2:30remaining
Which option correctly uses Flask's request validation with Marshmallow schema?

Given a Marshmallow schema UserSchema to validate incoming JSON, which Flask route code correctly validates and returns errors if invalid?

Flask
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
A
data = request.json
schema = UserSchema()
validated = schema.validate(data)
if validated:
    return jsonify(validated), 400
return jsonify(data), 201
B
data = request.get_json(force=True)
schema = UserSchema()
validated = schema.load(data)
return jsonify(validated), 201
C
data = request.get_json()
schema = UserSchema()
try:
    validated = schema.load(data)
except ValidationError as err:
    return jsonify(err.messages), 400
return jsonify(validated), 201
D
data = request.get_json()
schema = UserSchema()
validated = schema.dump(data)
return jsonify(validated), 201
Attempts:
2 left
💡 Hint

Remember that load validates and deserializes, and raises ValidationError on failure.

🔧 Debug
advanced
2:00remaining
Why does this Flask route always return 400 even with valid JSON?

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?

Flask
@app.route('/data', methods=['POST'])
def data():
    data = request.get_json(force=True)
    if not data:
        return {'error': 'No data'}, 400
    return {'received': data}
AUsing force=True causes get_json to always return None on valid JSON.
BThe JSON sent is an empty object {}, which is falsy in Python, triggering the error.
CThe route is missing content-type check, so get_json returns None even for valid JSON.
DThe request method is not POST, so get_json returns None.
Attempts:
2 left
💡 Hint

Think about how Python treats empty dictionaries in boolean contexts.

🧠 Conceptual
expert
3:00remaining
Which statement best describes Flask request validation best practices?

Choose the best practice for validating incoming JSON requests in Flask applications.

AUse a validation library like Marshmallow to define schemas and handle validation and error reporting cleanly.
BAlways use <code>request.get_json(force=True)</code> and manually check keys to ensure data validity.
CTrust client data and validate only after processing to improve performance.
DUse <code>request.data</code> and parse JSON manually with <code>json.loads</code> to control validation.
Attempts:
2 left
💡 Hint

Consider maintainability and clear error handling in your choice.