Intermediate interview questions in Python & FastAPI, page 2

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.

How do you safely execute blocking code from an async function
Tests whether you know how to prevent event loop blocking by offloading sync work. Name asyncio.to_thread or run_in_executor, explain ThreadPoolExecutor scheduling, and note when processes beat threads.

Explain the asyncio event loop and cooperative multitasking
Tests if you view the event loop as a single-threaded orchestrator, not magic parallelism. Strong answers note it runs tasks and callbacks, manages a ready queue, and yields control at await. Red flag: calling it multithreading or parallel execution.
asyncio.gather vs asyncio.wait
Gather returns ordered results and propagates the first exception (or captures them); wait returns done/pending sets and never raises, you inspect each.

When should you use asyncio.Lock over threading.Lock?
This tests cooperative multitasking knowledge: asyncio.Lock yields to the event loop via await, while threading.Lock blocks the OS thread and freezes the loop. A red flag is claiming threading.Lock works because locks are universal.

How do you use FastAPI dependency injection for database sessions?
Build a generator dependency that yields a session and closes it after; inject via Depends(get_db).

Why synchronous DB libraries block async FastAPI endpoints and correct SQLAlchemy usage
This tests event loop blocking: sync DB calls in async def halt all requests. Answer: sync drivers block the loop despite releasing the GIL; use asyncpg with SQLAlchemy create_async_engine and AsyncSession. Red flag: recommending run_in_executor as default.
Implement a PATCH endpoint for partial SQLAlchemy updates
Tests PATCH vs PUT and selective ORM updates. Strong answer: all-optional update schema, load existing record, iterate exclude_unset=True fields with setattr, commit. Red flag: updating without excluding unset, which overwrites missing fields with None.
MongoDB async ODM vs SQLAlchemy sessions
Motor client as a connection pool with no SQLAlchemy-style session or transaction; Beanie document models over Motor; initialize once at startup and await find queries.

Implement OAuth2 Password Flow in FastAPI
Tests FastAPI security integration and stateless auth patterns. A strong answer covers the POST /token endpoint returning a JWT, the OAuth2PasswordBearer dependency, and get_current_user decoding the JWT sub.

Implement RBAC in FastAPI with a JWT role dependency
Build a dependency that decodes the JWT, checks the role, raises 403 if not admin, and inject via Depends.

How do OAuth2 scopes enable granular permissions in FastAPI versus role-based checks?
Tests OAuth2 scope granularity vs RBAC and FastAPI SecurityScopes. Strong answers mention JWT claim strings, SecurityScopes per endpoint, and that RBAC is coarse while scopes are fine-grained. Red flag: treating scopes as roles or skipping claim checks.
Write a FastAPI middleware that adds X-Process-Time header
Tests FastAPI lifecycle and header mutation. Strong answers use the http middleware decorator, await call_next, compute elapsed time, and inject X-Process-Time before returning. Red flag: forgetting to await call_next or mutating headers after the return.
Which FastAPI CORSMiddleware parameters beyond allow_origins fix a PUT preflight?
Configure allow_methods for PUT and allow_headers for Authorization so the browser approves the cross-origin call.
Propagating a correlation ID without parameter passing
Middleware reads or generates the header, stores it in a contextvars.ContextVar, service code reads it anywhere, and logging filters inject it.
BackgroundTasks dependency vs response.background
The injected BackgroundTasks parameter lets endpoints and dependencies stack tasks and is the common path; response.background attaches a single Starlette task when you return a Response object…
Explain FastAPI dependency overrides with an in-memory SQLite test example
This tests FastAPI's hook for swapping dependencies cleanly in tests. A strong answer names app.dependency_overrides, defines a test-only in-memory SQLite session, and handles teardown. A red flag is patching globals or mocking ORM instead of dependency.
How do you test a FastAPI endpoint without real tokens?
Tests whether you know FastAPI's dependency override mechanism to isolate business logic from auth. A great answer describes using app.dependency_overrides to swap the auth Depends for a mock returning a fake user, then cleaning up after the test.
How would you use pytest fixtures to manage TestClient and mock dependencies?
Tests FastAPI test isolation and dependency overrides. Strong answer: function-scoped fixture yielding TestClient, mock injection via app.dependency_overrides, and teardown cleanup to prevent state leaks.

How do you document multiple response schemas in OpenAPI?
This tests FastAPI OpenAPI schema generation for error responses. A strong answer covers the decorator responses dict mapping status codes to Pydantic models and descriptions, plus manually returning JSONResponse with that code.
We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.
See open roles