Python / FastAPI Basics Interview Questions
What are the most important FastAPI best practices for a production-ready API?
A well-architected FastAPI project follows consistent patterns across structure, validation, security, and operations. Here is a consolidated reference.
| Area | Best Practice |
|---|---|
| Project structure | Separate concerns: routers/, models/, schemas/, dependencies/, services/ |
| Pydantic models | Separate Input/Output models; never return password fields; use Field() for constraints |
| Dependencies | Use Depends() for DB sessions, auth, pagination — keep routes thin |
| Authentication | JWT with short expiry + refresh tokens; hash passwords with bcrypt/argon2 |
| Database | Async SQLAlchemy + asyncpg; connection pool sized to workers; run Alembic in CI/CD |
| Error handling | Custom exception handlers for consistent error format; never expose stack traces |
| Testing | 100% route coverage with TestClient; override dependencies for isolation |
| Configuration | pydantic-settings + .env; never hardcode secrets; use secret managers in prod |
| Deployment | Gunicorn + UvicornWorker; non-root Docker user; health check endpoint |
| Observability | Structured JSON logs; /metrics for Prometheus; distributed tracing with OpenTelemetry |
| Docs | Meaningful summaries/descriptions; hide /docs in production; version the API |
# Recommended project layout # . # âââ app/ # â âââ main.py # FastAPI() instance, lifespan, include_router # â âââ config.py # pydantic-settings Settings class # â âââ database.py # engine, AsyncSessionLocal, Base # â âââ dependencies.py # get_db, get_current_user, pagination # â âââ routers/ # â â âââ users.py # APIRouter for /users # â â âââ items.py # APIRouter for /items # â âââ models/ # â â âââ user.py # SQLAlchemy ORM models # â âââ schemas/ # â â âââ user.py # Pydantic in/out schemas # â âââ services/ # â âââ user_service.py # business logic, DB queries # âââ tests/ # â âââ conftest.py # fixtures, TestClient # â âââ test_users.py # âââ alembic/ # migrations # âââ Dockerfile # âââ docker-compose.yml # âââ requirements.txt
More Related questions...