API & Security Best Practices
Baseline security advocacy for Python HTTP services.
How to Use This List
- Review during design reviews and before production deploys.
- Convert repeat failures into automated CI policy where possible.
- Revisit after framework minor upgrades.
Transport
- HTTPS everywhere in production.
- Terminate TLS at proxy with modern cipher suites.
- Set HSTS for browser clients.
Auth
- Authenticate every protected route.
- Use short-lived access tokens and refresh rotation.
- Hash passwords with argon2 or bcrypt.
Input
- Validate and sanitize at the boundary.
- Parameterize SQL; avoid shell string composition.
- Cap payload sizes at proxy and app.
Operations
- Run pip-audit or uv audit in CI.
- Store secrets in vaults, not git.
- Log security events without sensitive values.
FAQs
When should I adopt API security baseline?
Use it when the patterns and trade-offs on this page match your API or data boundary.
What is the top production mistake with API security baseline?
Skipping validation, timeouts, or explicit error contracts at the HTTP edge.
How do I test API security baseline?
Use the framework test client, override dependencies, and assert status plus JSON shape.
Does API security baseline work with Python 3.14?
Yes - examples target Python 3.14 with pinned framework versions from the stack footer.
How does API security baseline relate to Pydantic 2?
Validate and serialize at boundaries; keep services working with typed domain objects.
Sync or async?
Prefer async routes when I/O dominates; keep CPU work small or offload to workers.
Where should business logic live?
Thin handlers; services own rules; repositories own queries.
How do I document APIs?
Publish OpenAPI or schema docs that match response models in code.
How do I handle versioning?
Explicit URL or header versioning with deprecation windows - avoid silent breaks.
What should I read next?
Follow the Related links for the next layer of depth in this section.
How do I stay secure?
Authenticate callers, authorize per resource, rate-limit, and never log secrets.
Performance first step?
Measure DB and upstream latency before swapping frameworks.
Related
- API Design Basics - REST conventions
- OAuth2 & JWT - Token flows
- Secrets Management - Env and vaults
- Input Validation & Injection - Defenses
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.