Python
217 bites tagged Python — interview questions with model answers, and 60-second explainers.
How do you manage service lifecycle with FastAPI Depends versus formal DI?
Tests scaling FastAPI DI beyond routes. Answer: use Depends(yield) for request-scoped DB sessions; use a formal container for deep singleton service graphs and lifespan wiring; hybrid is best. Red flag: using Depends for everything and ignoring testability.
How do you dynamically discover and register FastAPI routers from a directory?
Scan app/routers/ with importlib, validate APIRouter objects, include_router with prefixes, and isolate failures. You can safely register FastAPI routers via dynamic imports.
How do you apply a common path prefix across FastAPI routers?
Tests whether you know APIRouter decouples routes from path prefixes. Use relative paths in APIRouter, then mount with app.include_router(router, prefix="/api/v1"). This keeps modules reusable. Red flag: hardcoding the full absolute path in every decorator.
Manage dev, staging, and prod configs in a large FastAPI app
This tests separating environment config from code with pydantic-settings and env vars. A strong answer covers .env files for local dev, per-environment validation, and secret injection for prod. Red flags are hardcoded values or scattered conditionals.
How to apply a dependency to only one FastAPI router?
Pass dependencies=[Depends(auth)] to APIRouter for /users, omit it for /items, include both. router-level dependency injection in FastAPI. repeating Depends() on every route or using middleware.
How do you include a router in your main FastAPI app?
Create APIRouter in another file, import it into main.py, then call app.include_router(router). knowledge of the APIRouter wiring pattern. rewriting endpoints manually in main.py rather than using include_router.
Describe a common FastAPI project structure and key directories
Main module holds the FastAPI app; domain files (users, items) expose APIRouters; dependencies in their own module; pyproject.toml as entrypoint. Scaling past one file with APIRouter and domain separation.
What is APIRouter in FastAPI and why use it?
It tests your grasp of modular architecture in FastAPI. APIRouter splits routes into separate modules so you include them in the main app with prefixes, tags, and dependencies.
Explain the internal role of the Depends class
A strong answer notes it marks parameters for solver, enables recursive sub-dependencies and Annotated sharing, and feeds OpenAPI. If you treat Depends as FastAPI's core DI declaration primitive.
How does lifecycle differ for global vs path operation dependencies?
Global deps run on every request to any route; path-local deps run only for that route; expensive setup belongs in a lifespan event or cached singleton, not a dependency. Per-request scoping in FastAPI.
How would you implement a dependency requiring multi-source parameters?
Tests if you know FastAPI resolves dependency params like endpoint params. Great answers annotate each parameter with its source inside the dependency so FastAPI injects them independently. Red flag: manually parsing Request or merging values in the endpoint.
How does FastAPI cache dependencies within a single request?
Tests if you know FastAPI caches a dependency after the first call in a request and reuses it across the tree. A strong answer covers default use_cache=True, request-scoped lifetime, and disabling it.
How does FastAPI execute setup and teardown in nested yield dependencies?
It tests FastAPI's dependency injection lifecycle and stack-like teardown for nested yield dependencies. Setup runs top-down; teardown runs bottom-up after the response. A red flag is claiming teardown order is arbitrary or follows garbage collection.
How do you use a Python class as a FastAPI dependency?
It tests whether you understand FastAPI DI beyond functions and when stateful encapsulation wins. Explain that Depends takes callable classes, centralizing setup and shared state in __init__. Red flag: claiming classes are pure syntactic sugar.
How would you override a FastAPI dependency during testing?
Tests your grasp of FastAPI's dependency override mechanism. A strong answer mentions app.dependency_overrides, notes that sub-dependencies are bypassed, and stresses clearing overrides after each test.
How do you apply a dependency to an APIRouter without per-endpoint signatures?
Pass Depends() to APIRouter dependencies parameter; runs before every route in that router and shows in docs. FastAPI router-level DI. using middleware or manual decorators over the native dependencies argument.
What is the purpose of yield in a dependency function?
Tests teardown logic in FastAPI dependencies. Yield splits setup from cleanup: code before yield runs pre-request, after yield runs post-response to close resources like DB sessions. Red flag: confusing it with return or thinking yield is only for generators.
How do you declare a function as a dependency, and why?
Tests FastAPI dependency injection basics. Answer: create a function, import Depends, and add it to path operation parameters so FastAPI injects it. Purpose: routes declare what they need instead of hard-coding shared logic.
Access raw request bytes in FastAPI for webhook verification
Tests FastAPI's Starlette integration and stream semantics. Outline: inject Request and await request.body, but the stream is single-use so JSON parsing later fails and docs are lost. Red flag: suggesting a Pydantic model still works after consuming the body.
How would you use BackgroundTasks to run work after returning a 201?
What it tests: FastAPI deferred execution and failure modes. A strong answer injects BackgroundTasks, adds the task, returns 201, and notes same-process post-response execution with no persistence. Red flag: Treating it as a distributed queue like Celery.
Implement a custom exception handler to catch ItemNotFoundError and return 404
Tests FastAPI exception handler registration beyond HTTPException. A strong answer covers creating a custom exception, using app.exception_handler, and returning a JSONResponse with status 404 and a structured body. Red flag: per-route try/except, plain dict.
How do you set a custom header and cookie in FastAPI?
Tests FastAPI temporal Response injection and merge behavior. Strong answer: inject Response, set headers via response.headers, cookies via set_cookie, then return the payload normally.
How do you create a reusable current-user dependency in FastAPI?
Tests DRY auth with FastAPI Depends. Answer: create get_current_user that Depends on OAuth2PasswordBearer, verifies token, returns User model, inject into routes. Red flag: middleware or manual header parsing in each endpoint.
Implement a FastAPI file upload endpoint with form data
Tests FastAPI multipart literacy. A strong answer names python-multipart, uses Annotated[UploadFile, File()] for the image, and Annotated[str, Form()] for user_id.
Get Python bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.