Skip to content
tezvyn:

Python & FastAPI

Python, Django, FastAPI, Flask, async Python

37 bites

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

Advanced interview questions in Python & FastAPI

How does Uvicorn use asyncio to handle thousands of concurrent connections?
advanced2 min read

How does Uvicorn use asyncio to handle thousands of concurrent connections?

Tests async concurrency and the GIL. Great answers cover the event loop suspending coroutines at await, Uvicorn interleaving connections, and multi-process workers for parallelism. Red flag: claiming asyncio uses threads per request or bypasses the GIL.

advanced2 min read

Implement an async database session dependency using yield for setup and teardown

This tests async resource lifecycle management in FastAPI. A strong answer uses async def, yields a session inside try, closes in finally, and injects with Depends. A red flag is omitting finally or using sync def for async I/O, which leaks connections.

Create a generic Pydantic BaseModel for API response wrappers
advanced2 min read

Create a generic Pydantic BaseModel for API response wrappers

Subclass BaseModel and Generic[T]; type data as T; use ResponseWrapper[User]; note unparametrized TypeVars validate as Any.

advanced2 min read

FastAPI non-integer query param default behavior

Tests FastAPI's automatic Pydantic validation and default error contracts. Strong answer: 422 Unprocessable Entity with JSON detail array containing loc, msg, and type fields. Red flag: saying 400 Bad Request or manual validation is needed.

How do you type-hint repeated query params in FastAPI?
advanced2 min read

How do you type-hint repeated query params in FastAPI?

Tests FastAPI's Annotated pattern for multi-value query strings. A great answer uses Annotated[list[str], Query()] = [] to collect repeated keys, and notes the old Query-as-default alternative. Red flag: manual parsing or typing it as str.

What is the :path converter in FastAPI?
advanced2 min read

What is the :path converter in FastAPI?

Tests FastAPI routing semantics and URL segmentation. A strong answer states :path captures slashes across segments while plain str stops at the next slash, and cites file-serving as the use case.

Ensure end_date is after start_date in Pydantic
advanced2 min read

Ensure end_date is after start_date in Pydantic

Tests whether you know field validators see only one value and cannot compare siblings. Use a model validator instead, which receives the full instance and can compare start_date and end_date. Red flag: a field validator referencing the other field.

advanced2 min read

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.

advanced2 min read

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.

advanced2 min read

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 implement a dependency requiring multi-source parameters?
advanced2 min read

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 lifecycle differ for global vs path operation dependencies?
advanced2 min read

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.

Explain the internal role of the Depends class
advanced2 min read

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.

advanced2 min read

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.

advanced2 min read

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.

advanced2 min read

Override a FastAPI dependency at the APIRouter level

Tests FastAPI DI scoping limits. Answer: APIRouter has no dependency_overrides; create a sub-app, apply overrides, mount it. Red flag: Claiming router-level overrides exist or mutating global app state.

Unhandled exception in asyncio.create_task(): consequence and detection
advanced2 min read

Unhandled exception in asyncio.create_task(): consequence and detection

Tests Task exception capture vs propagation. Good answer: exceptions are stored in the Task object, the loop keeps running, and the creator must await the task or call task.exception() to retrieve it; unretrieved ones may be logged.

How do you gracefully cancel and clean up an asyncio task?
advanced2 min read

How do you gracefully cancel and clean up an asyncio task?

This tests asyncio cooperative cancellation and cleanup. A strong answer covers catching CancelledError at await points, using try/finally or async context managers for cleanup, and re-raising.

Why are contextvars better than threading.local in async Python?
advanced2 min read

Why are contextvars better than threading.local in async Python?

This tests whether you know async tasks share OS threads, making thread-local storage unsafe for request state. A great answer notes ContextVar is task-local and resets automatically, while threading.local bleeds across concurrent coroutines.

advanced2 min read

How do you atomically create an order and update inventory?

Tests transaction boundaries and SQLAlchemy 2.0 session lifecycle in FastAPI. A strong answer wraps both writes in session.begin(), flushes to catch constraint errors early, and uses exceptions to trigger rollback.

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