Careeroza
Intermediate Interview Questions
What is dependency injection in FastAPI?
Declaring Depends(func) makes FastAPI call func before the endpoint and pass in its result. It is used for DB sessions, auth, settings and shared parameters. Dependencies can be chained, use yield for cleanup, be applied to routers/apps, and be replaced in tests with dependency_overrides.
async def or def for an endpoint?
Use async def when the endpoint awaits async libraries. Use plain def when it calls blocking code: FastAPI runs it in a thread pool. Calling blocking code inside async def blocks the event loop and hurts all requests.
How do you structure a large FastAPI project?
- One
APIRouterper resource, included inmain.py. - Separate Pydantic schemas from DB models.
- Business logic in service modules.
- Settings via pydantic-settings and environment variables.
- Alembic for migrations; tests with TestClient and pytest.
What is response_model?
It declares the response schema: FastAPI validates and filters the returned data (removing fields like password hashes) and documents the shape in OpenAPI.
How do you handle CORS?
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_methods=["*"],
allow_headers=["*"],
)