Skip to content
tezvyn:

Python & FastAPI

Python, Django, FastAPI, Flask, async Python

133 bites

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

Interview questions in Python & FastAPI, page 4

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.

Describe SQLAlchemy setup in FastAPI from database config to endpoint
easy2 min read

Describe SQLAlchemy setup in FastAPI from database config to endpoint

Tests FastAPI dependency injection and SQLAlchemy session lifecycle. Good answers cover: engine with pooling, declarative models, a yield-based session dependency, and endpoint queries. Red flag: engine per request or global session shared everywhere.

Explain SQLAlchemy ORM vs Pydantic models in FastAPI
easy2 min read

Explain SQLAlchemy ORM vs Pydantic models in FastAPI

This tests separation of database schema from API contracts. A strong answer distinguishes SQLAlchemy table rows from Pydantic validation and OpenAPI generation, and notes that create schemas exclude auto-generated IDs.

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

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.

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.

intermediate1 min read

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.

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.

advanced1 min read

SQLAlchemy connection pooling across Uvicorn workers

Each worker has its own pool; total DB connections equal workers times (pool_size plus max_overflow); overflow connections are temporary; misconfiguration exhausts DB…

How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?
easy2 min read

How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?

OAuth2PasswordBearer sets the token URL, Depends injects it into the endpoint, and FastAPI validates the Bearer header.

What are the three components of a JWT?
easy2 min read

What are the three components of a JWT?

Tests if you know JWT structure beyond library usage. A strong answer lists header, payload, and signature; notes Base64Url encoding; and gives a registered claim like exp. A red flag is confusing signing with encryption.

easy2 min read

How should you store user passwords in a database?

Tests knowledge of slow salted hashing versus encryption. Strong answers pick Argon2id or bcrypt, require unique per-user salts, describe verification via re-hashing with constant-time comparison, and cite bcrypt or argon2-cffi.

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.

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.

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.

advanced1 min read

Revoking stateless JWTs on logout

A server-side denylist of revoked token IDs checked per request, or short-lived access tokens paired with revocable refresh tokens.

advanced2 min read

What JWT claims must you validate beyond the signature?

This tests whether you understand token misuse beyond crypto: time validity, audience and issuer binding, algorithm whitelisting, and required claims enforcement. Red flag: only checking signature and ignoring exp or aud.

easy2 min read

Frontend on localhost:3000 gets errors calling FastAPI on localhost:8000. Name and fix?

This tests whether different ports mean different origins, causing CORS errors. A strong answer names CORS, notes ports are distinct origins, and outlines using CORSMiddleware with allow_origins.

easy2 min read

How do you send an email without blocking a FastAPI request?

Tests knowledge of FastAPI's BackgroundTasks for post-response work. Strong answer: import it, inject into the endpoint, define a task function, and call add_task before returning.

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