Chapter 29: Security Best Practices
Security in Python web apps is a combination of framework features, dependencies, deployment, and habits.
Core checklist:
- Validate all input at boundaries.
- Use parameterized SQL through SQLAlchemy.
- Escape HTML output; do not mark user content safe.
- Add CSRF protection to cookie-authenticated form posts.
- Use secure cookies.
- Hash passwords with modern password hash algorithms.
- Rate-limit login, reset, and expensive endpoints.
- Keep dependencies updated and scan them.
- Do not expose debug tracebacks in production.
- Keep secrets out of Git.
- Use least privilege database credentials.
- Add authorization tests for sensitive workflows.
FastAPI is excellent for APIs, but it does not automatically provide every browser security feature that Django includes. If you build server-rendered forms in FastAPI, explicitly add CSRF protection and secure session handling.