PYTHON

Implement Strict Server-Side Data Validation for API Endpoints in Flask

Ensure data integrity and prevent injection attacks by rigorously validating all incoming API request data on the server-side in Python Flask applications.

from flask import Flask, request, jsonify
from werkzeug.exceptions import BadRequest

app = Flask(__name__)

@app.route('/api/users', methods=['POST'])
def create_user():
    try:
        data = request.get_json()
        if not data:
            raise BadRequest('Request body must be JSON')

        # Strict validation of expected fields and types
        username = data.get('username')
        email = data.get('email')
        age = data.get('age')

        if not isinstance(username, str) or not (3 <= len(username) <= 50):
            raise BadRequest('Username must be a string between 3 and 50 characters.')
        
        # Basic email regex for format, full validation requires more robust checks
        import re
        if not isinstance(email, str) or not re.match(r'^[\w\.-]+@[\w\.-]+$', email):
            raise BadRequest('Email must be a valid string format.')

        if not isinstance(age, int) or not (1 <= age <= 120):
            raise BadRequest('Age must be an integer between 1 and 120.')
        
        # Further checks could include uniqueness for username/email, etc.

        # Process the validated data
        # user_id = save_user_to_db(username, email, age)
        return jsonify({
            'message': 'User created successfully',
            'user': {'username': username, 'email': email, 'age': age}
        }), 201

    except BadRequest as e:
        return jsonify({'error': str(e)}), 400
    except Exception as e:
        return jsonify({'error': 'An unexpected error occurred.'}), 500

if __name__ == '__main__':
    app.run(debug=True)
How it works: This Flask snippet demonstrates crucial server-side input validation for API endpoints. It ensures that incoming JSON data is present and strictly conforms to expected types (e.g., `username` as a string, `age` as an integer) and constraints (e.g., string length, numeric range). This robust validation prevents malformed data from being processed, mitigating a wide range of vulnerabilities including potential injection attacks (beyond SQL) and application logic errors caused by unexpected input.

Need help integrating this into your project?

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

Hire DigitalCodeLabs