All bites
The whole library, newest first. Filter by what you are here for, or pick a topic if you already know.
8664 bites
Page 6

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.
Overriding FastAPI Dependencies for Testing
Overriding dependencies lets you swap real components for fakes during tests. This is vital for isolating tests from external services like auth providers or databases, letting you control inputs and avoid slow, flaky network calls.
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.
Accessing the Raw Request Object in FastAPI
Think of it as dropping to a lower level. Instead of FastAPI handing you validated data, you grab the raw Starlette HTTP request yourself. Use this for data not covered by standard declarations, like a client's IP.

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.
FastAPI's APIRouter: Grouping Routes into Modules
Think of APIRouter as a mini-FastAPI app for organizing endpoints. It lets you group related paths, like all user routes, into a separate file. This is crucial for keeping large applications maintainable.

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

FastAPI: Splitting Your App with `include_router`
app.include_router is like plugging a pre-wired power strip of API endpoints into your main FastAPI app. It lets you organize a large app into smaller files by feature, then combine them. The footgun is forgetting to add a URL prefix for each router.

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

Pydantic BaseSettings: Typed, Layered Configuration
Pydantic's BaseSettings treats configuration as typed data, not just strings. It automatically loads and validates settings from environment variables, .env files, and secrets stores into a Python object.

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?
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.
FastAPI: Managing Environment-Specific Settings
Treat app configuration like a contract, not hardcoded values. Pydantic Settings defines required variables (like API keys) and loads them from the environment, preventing you from shipping dev settings to production.
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.

FastAPI: Mounting Independent Sub-Applications
Mounting delegates a URL prefix to a separate FastAPI app, giving it its own isolated logic and API docs. Use it to combine microservices or isolate domains. The footgun: the main app's dependencies and middleware do not apply to the sub-app.
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.