Skip to content
tezvyn:

Python & FastAPI

Python, Django, FastAPI, Flask, async Python

110 bites

Test yourself: Top 30 intermediate Python & FastAPI interview questionsMultiple choice, with the correct answer and why it is correct on every question. Free, no sign-in.

Intermediate everything in Python & FastAPI, page 2

How do you authenticate a FastAPI WebSocket connection?
intermediate2 min read

How do you authenticate a FastAPI WebSocket connection?

This tests WebSocket limits and FastAPI dependency injection. Pass the JWT via query parameter or cookie at handshake, validate it with Depends, and reject with HTTP 403 or 1008 close.

intermediate2 min read

Use startup events to initialize a database pool and inject it

This tests FastAPI lifespan hooks and dependency injection for shared state. A strong answer creates the pool in an async startup handler, stores it on app.state, and accesses it via a dependency in routes. A red flag is creating a fresh pool per request.

How do you handle a WebSocket client disconnect in FastAPI?
intermediate2 min read

How do you handle a WebSocket client disconnect in FastAPI?

Cite installing websockets, Handling disconnections and multiple clients pattern, and Depends.

How do you mark a FastAPI endpoint as deprecated?
intermediate2 min read

How do you mark a FastAPI endpoint as deprecated?

This tests decorator-level OpenAPI configuration in FastAPI. Pass deprecated=True to the path operation decorator, e.g. @app.get("/old", deprecated=True), so Swagger UI shows a strikethrough. Red flag: burying a deprecation warning in the docstring instead.

How do you group FastAPI endpoints under tags and describe groups?
intermediate2 min read

How do you group FastAPI endpoints under tags and describe groups?

Tests FastAPI's two-step tag system: decorators label routes, and openapi_tags supplies group descriptions. Good answers cover tagging paths with tags=["users"], then defining metadata in FastAPI(openapi_tags=[...]) with matching names.

intermediate2 min read

How can you provide a Swagger UI example for a Pydantic body?

Tests whether you know FastAPI generates OpenAPI schema from Pydantic metadata. A strong answer names Field(example=...) for per-field samples and Body(example=...) for the full payload.

How do you document multiple response schemas in OpenAPI?
intermediate2 min read

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.

intermediate2 min read

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.

intermediate2 min read

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.

intermediate2 min read

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.

intermediate2 min read

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.

intermediate2 min read

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.

How do OAuth2 scopes enable granular permissions in FastAPI versus role-based checks?
intermediate2 min read

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.

Implement RBAC in FastAPI with a JWT role dependency
intermediate2 min read

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.

Implement OAuth2 Password Flow in FastAPI
intermediate2 min read

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.

intermediate2 min read

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.

Why synchronous DB libraries block async FastAPI endpoints and correct SQLAlchemy usage
intermediate2 min read

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.

How do you use FastAPI dependency injection for database sessions?
intermediate2 min read

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).

When should you use asyncio.Lock over threading.Lock?
intermediate2 min read

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.

Explain the asyncio event loop and cooperative multitasking
intermediate2 min read

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.

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