PYTHON

Robust Server-Side Input Validation in Python Flask

Implement robust server-side input validation in Flask using Pydantic to ensure data integrity, prevent common security vulnerabilities, and handle malformed requests.

from flask import Flask, request, jsonify
from pydantic import BaseModel, Field, ValidationError

app = Flask(__name__)

class UserData(BaseModel):
    username: str = Field(min_length=3, max_length=50)
    email: str = Field(pattern=r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
    age: int = Field(gt=0, le=120)

@app.route('/register', methods=['POST'])
def register_user():
    try:
        user_data = UserData(**request.json)
        # If validation passes, process user_data (e.g., save to database)
        return jsonify({"message": f"User {user_data.username} registered successfully."}), 200
    except ValidationError as e:
        return jsonify({"errors": e.errors()}), 400
    except Exception as e:
        return jsonify({"message": f"An unexpected error occurred: {str(e)}"}), 500

if __name__ == '__main__':
    app.run(debug=True)
How it works: This Flask snippet demonstrates robust server-side input validation using Pydantic. It defines a `UserData` schema with specific validation rules for fields like `username` (min/max length), `email` (regex pattern), and `age` (greater than 0, less than or equal to 120). When a POST request is received, the incoming JSON data is parsed and validated against this schema. If validation fails, a `400 Bad Request` response with detailed error messages is returned, preventing invalid or potentially malicious data from being processed by the application logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs