Bird
Raised Fist0
Flaskframework~20 mins

Request validation in Flask - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of request validation in a Flask application?
easy
A. To store user data permanently
B. To check incoming data for correctness and safety
C. To style the HTML forms automatically
D. To speed up the server response time

Solution

  1. Step 1: Understand what request validation means

    Request validation means checking the data sent by users to make sure it is correct and safe to use.
  2. Step 2: Identify the main goal of validation

    The main goal is to prevent bad or harmful data from causing errors or security problems.
  3. Final Answer:

    To check incoming data for correctness and safety -> Option B
  4. Quick Check:

    Request validation = check data safety [OK]
Hint: Validation means checking data is safe and correct [OK]
Common Mistakes:
  • Thinking validation speeds up the server
  • Confusing validation with styling
  • Assuming validation stores data
2. Which of the following is the correct way to access JSON data from a Flask request object?
easy
A. request.get_json()
B. request.json_data
C. request.json()
D. request.data.json

Solution

  1. Step 1: Recall Flask's method to get JSON data

    Flask provides the method get_json() to parse JSON from the request body.
  2. Step 2: Check each option for correctness

    request.json() uses parentheses but json is a property, not a method. request.json_data and D are not valid Flask attributes.
  3. Final Answer:

    request.get_json() -> Option A
  4. Quick Check:

    Use get_json() to read JSON data [OK]
Hint: Use request.get_json() to read JSON in Flask [OK]
Common Mistakes:
  • Calling request.json as a function
  • Using non-existent attributes like json_data
  • Trying to access JSON via request.data.json
3. Given this Flask route code, what will be the output if the JSON request body is {"age": 17}?
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/check', methods=['POST'])
def check_age():
    data = request.get_json()
    if data and data.get('age', 0) >= 18:
        return jsonify({'status': 'allowed'})
    else:
        return jsonify({'status': 'denied'})
medium
A. {"status": "allowed"}
B. Empty response
C. 500 Internal Server Error
D. {"status": "denied"}

Solution

  1. Step 1: Analyze the JSON input and condition

    The input JSON has "age": 17. The code checks if age is 18 or more.
  2. Step 2: Determine which branch runs

    Since 17 is less than 18, the else branch runs, returning {'status': 'denied'}.
  3. Final Answer:

    {"status": "denied"} -> Option D
  4. Quick Check:

    Age 17 < 18 = denied [OK]
Hint: Check if age >= 18 to allow, else deny [OK]
Common Mistakes:
  • Assuming 17 is allowed
  • Expecting server error for valid JSON
  • Thinking response is empty
4. What is wrong with this Flask code snippet for validating a required 'username' field in JSON?
data = request.get_json()
if 'username' in data:
    return 'Username received'
else:
    return 'Missing username', 400
medium
A. It does not check if data is None before accessing
B. It uses wrong HTTP status code for error
C. It should use request.json instead of get_json()
D. It should return JSON response, not plain text

Solution

  1. Step 1: Understand get_json() behavior

    request.get_json() can return None if no JSON is sent or invalid JSON.
  2. Step 2: Identify the error in code

    The code accesses 'username' in data without checking if data is None, causing a crash if data is None.
  3. Final Answer:

    It does not check if data is None before accessing -> Option A
  4. Quick Check:

    Check data is not None before key access [OK]
Hint: Always check if get_json() returned data before use [OK]
Common Mistakes:
  • Ignoring None check on JSON data
  • Confusing status codes
  • Thinking request.json is better than get_json()
  • Assuming plain text is always wrong
5. You want to validate a JSON request in Flask to ensure it has a 'name' string and an 'age' integer above 0. Which approach best combines validation and clear error messages?
hard
A. Manually check keys and types, return custom error messages on failure
B. Use request.get_json() and assume data is always correct
C. Use a library like marshmallow to define a schema and validate automatically
D. Skip validation and handle errors later in the code

Solution

  1. Step 1: Consider manual validation drawbacks

    Manual checks can be error-prone and verbose, making code hard to maintain.
  2. Step 2: Understand benefits of marshmallow

    Marshmallow lets you define clear schemas and automatically validates input, returning helpful error messages.
  3. Step 3: Evaluate other options

    Assuming data is correct or skipping validation risks bugs and security issues.
  4. Final Answer:

    Use a library like marshmallow to define a schema and validate automatically -> Option C
  5. Quick Check:

    Use marshmallow for clear, automatic validation [OK]
Hint: Use marshmallow for easy, clear validation [OK]
Common Mistakes:
  • Assuming data is always valid
  • Writing complex manual checks
  • Ignoring validation completely
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard