Request validation helps check if the data sent to your Flask app is correct and safe before using it.
Request validation in Flask
from flask import request # Access data value = request.form.get('field_name') # Simple manual validation example if not value: return 'Missing field_name', 400
Flask's request object holds all incoming data.
You can check data manually or use libraries like marshmallow or pydantic for easier validation.
from flask import request @app.route('/submit', methods=['POST']) def submit(): name = request.form.get('name') if not name: return 'Name is required', 400 return f'Hello, {name}!'
from flask import request, jsonify @app.route('/json', methods=['POST']) def json_route(): data = request.get_json() if not data or 'age' not in data: return jsonify({'error': 'Age is required'}), 400 return jsonify({'age': data['age']})
marshmallow to validate JSON data with required fields and email format.from flask import request from marshmallow import Schema, fields, ValidationError class UserSchema(Schema): username = fields.Str(required=True) email = fields.Email(required=True) @app.route('/user', methods=['POST']) def user(): json_data = request.get_json() try: data = UserSchema().load(json_data) except ValidationError as err: return err.messages, 400 return f"User {data['username']} with email {data['email']} created"
This Flask app has a /login route that expects JSON with 'username' and 'password'. It uses marshmallow to check the data. If data is missing or wrong, it sends back errors. If all is good, it welcomes the user.
from flask import Flask, request, jsonify from marshmallow import Schema, fields, ValidationError app = Flask(__name__) class LoginSchema(Schema): username = fields.Str(required=True) password = fields.Str(required=True) @app.route('/login', methods=['POST']) def login(): json_data = request.get_json() if not json_data: return jsonify({'error': 'No input data provided'}), 400 try: data = LoginSchema().load(json_data) except ValidationError as err: return jsonify(err.messages), 400 return jsonify({'message': f"Welcome, {data['username']}!"}) if __name__ == '__main__': app.run(debug=True)
Always check if request.get_json() returns data before validating.
Using validation libraries helps avoid repetitive manual checks and gives clear error messages.
Return HTTP status code 400 for bad input to inform clients properly.
Request validation checks incoming data to keep your app safe and working well.
You can validate form data or JSON using simple checks or libraries like marshmallow.
Good validation improves user experience by giving clear errors and prevents bugs.
Practice
Solution
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.Step 2: Identify the main goal of validation
The main goal is to prevent bad or harmful data from causing errors or security problems.Final Answer:
To check incoming data for correctness and safety -> Option BQuick Check:
Request validation = check data safety [OK]
- Thinking validation speeds up the server
- Confusing validation with styling
- Assuming validation stores data
Solution
Step 1: Recall Flask's method to get JSON data
Flask provides the methodget_json()to parse JSON from the request body.Step 2: Check each option for correctness
request.json() uses parentheses butjsonis a property, not a method. request.json_data and D are not valid Flask attributes.Final Answer:
request.get_json() -> Option AQuick Check:
Use get_json() to read JSON data [OK]
- Calling request.json as a function
- Using non-existent attributes like json_data
- Trying to access JSON via request.data.json
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'})Solution
Step 1: Analyze the JSON input and condition
The input JSON has "age": 17. The code checks if age is 18 or more.Step 2: Determine which branch runs
Since 17 is less than 18, the else branch runs, returning {'status': 'denied'}.Final Answer:
{"status": "denied"} -> Option DQuick Check:
Age 17 < 18 = denied [OK]
- Assuming 17 is allowed
- Expecting server error for valid JSON
- Thinking response is empty
data = request.get_json()
if 'username' in data:
return 'Username received'
else:
return 'Missing username', 400Solution
Step 1: Understand get_json() behavior
request.get_json() can return None if no JSON is sent or invalid JSON.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.Final Answer:
It does not check if data is None before accessing -> Option AQuick Check:
Check data is not None before key access [OK]
- Ignoring None check on JSON data
- Confusing status codes
- Thinking request.json is better than get_json()
- Assuming plain text is always wrong
Solution
Step 1: Consider manual validation drawbacks
Manual checks can be error-prone and verbose, making code hard to maintain.Step 2: Understand benefits of marshmallow
Marshmallow lets you define clear schemas and automatically validates input, returning helpful error messages.Step 3: Evaluate other options
Assuming data is correct or skipping validation risks bugs and security issues.Final Answer:
Use a library like marshmallow to define a schema and validate automatically -> Option CQuick Check:
Use marshmallow for clear, automatic validation [OK]
- Assuming data is always valid
- Writing complex manual checks
- Ignoring validation completely
Ready to prove it?
Pass the test and this pattern moves unknown
