← Back to all snippets
PYTHON

Implement Robust Server-Side Input Validation in Python Flask

Secure your Flask API by implementing comprehensive server-side input validation, ensuring data integrity and preventing common vulnerabilities like injection attacks.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/submit_data', methods=['POST'])
def submit_data():
    data = request.get_json()

    if not data:
        return jsonify({"error": "No input data provided"}), 400

    # Validate 'name' field
    name = data.get('name')
    if not name or not isinstance(name, str) or len(name) < 2 or len(name) > 50:
        return jsonify({"error": "Name is required, must be a string between 2 and 50 characters"}), 400

    # Validate 'age' field
    age = data.get('age')
    if not age or not isinstance(age, int) or age < 18 or age > 120:
        return jsonify({"error": "Age is required, must be an integer between 18 and 120"}), 400

    # Validate 'email' field (basic format check)
    email = data.get('email')
    if not email or not isinstance(email, str) or '@' not in email or '.' not in email:
        return jsonify({"error": "Valid email is required"}), 400

    # Simulate processing the valid data
    processed_data = {
        "id": 123, # Example ID
        "name": name.strip(), # Sanitize if needed
        "age": age,
        "email": email.lower(),
        "status": "processed"
    }

    return jsonify(processed_data), 200

if __name__ == '__main__':
    app.run(debug=True)
How it works: This Flask snippet demonstrates essential server-side input validation for a JSON API endpoint. It checks for the presence, type, and reasonable range/length of incoming data fields (`name`, `age`, `email`). By performing strict validation on the server, you ensure that only well-formed and expected data is processed, preventing many common vulnerabilities, data corruption, and application errors, even if client-side validation fails or is bypassed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs