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 10

Add a custom x- field to a FastAPI path operation schema
Tests knowledge of FastAPI's built-in OpenAPI extension hook. Answer: cite the path operation decorator's extra-schema dict (OpenAPI Extra) to merge x-internal-id directly. Red flag: proposing manual JSON editing or schema post-processing.
Custom FastAPI Middleware: The BaseHTTPMiddleware Helper
FastAPI's BaseHTTPMiddleware lets you wrap endpoints to run code before and after they execute. Use it to add custom headers or log request times. The footgun: reading request.body() in the middleware will break the endpoint, as the body can only be read…

How do you disable FastAPI docs but keep the OpenAPI schema?
Tests FastAPI constructor routing: docs_url, redoc_url, and openapi_url. Answer: pass docs_url=None and redoc_url=None while keeping openapi_url="/openapi.json", gated by env var. Red flag: middleware or manual route deletion instead of native configuration.
How do you directly modify FastAPI's generated OpenAPI dictionary?
Tests deep FastAPI lifecycle knowledge. Override app.openapi: save the original, call it to get the dict, mutate it, cache on app.openapi_schema, and return. Red flag: rewriting /openapi.json in middleware or touching the schema cache directly.

How do you define a WebSocket endpoint in FastAPI?
Import WebSocket, use @app.websocket, await accept, receive_text, then send_text.
What are startup and shutdown events in FastAPI?
Tests app lifespan hooks and resource lifecycle. Startup creates DB pools before traffic arrives; shutdown closes them after the last request. These decorators are deprecated; prefer lifespan context managers. Red flag: per-request middleware.

How do you handle a WebSocket client disconnect in FastAPI?
Cite installing websockets, Handling disconnections and multiple clients pattern, and Depends.

Celery: Offloading Work from Your FastAPI App
Celery lets your web app offload slow tasks to a separate process, keeping your API responsive. Use it for tasks that can't finish in a single HTTP request, like sending bulk emails or processing images.
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.
FastAPI's TestClient: Test Your API Without a Live Server
FastAPI's TestClient simulates API requests in-memory, letting you test endpoints without a live server. Use it with pytest to verify status codes and responses. The main footgun is forgetting to pip install httpx, as it's a required dependency.

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.
pytest Fixtures: Reusable Test Setups
Pytest fixtures are reusable functions for test setup, like creating sample data. Your tests request them by name as arguments, and pytest automatically runs them and injects the results.
WebSocket connection manager and broadcast
A manager class holding a list of active connections, connect accepts and appends, disconnect removes, broadcast iterates sending to each, all wrapped in try/finally to handle disconnects.

How do you broadcast WebSocket messages to all clients across server nodes?
Tests WebSocket horizontal scaling and pub/sub backplanes. A strong answer names a broker like Redis, describes cross-node fan-out, and keeps connection state purely local.
Run One Test with Many Inputs using pytest.parametrize
Run one test function with many inputs using @pytest.mark.parametrize, avoiding repetitive code. It's ideal for checking a function against various inputs, edge cases, and expected failures. The footgun: mutable parameters like lists are passed by reference.
How do you handle slow startup without blocking the FastAPI event loop?
It tests FastAPI lifespan events and event loop hygiene. Use an async lifespan to offload blocking model loading to a thread pool, track readiness with a global flag, and return 503 for early requests. Never block the event loop in startup handlers.
Testing Async FastAPI with pytest-asyncio
To test async code, your tests must also be async. pytest-asyncio lets you write async def test_... functions to await operations like database checks after an API call.

How do you inspect WebSocket close codes in FastAPI?
Tests WebSocket lifecycle handling in FastAPI. Strong answers catch the disconnect exception, read its code attribute, and log 1000 for normal closures versus 1001/1006 for crashes.
Testing FastAPI Lifespan Events
FastAPI lifespan events only run when TestClient is used as a context manager. Use this to test startup logic like DB pools before endpoints. Using TestClient(app) without with skips lifespan, leaving your app uninitialized and tests silently wrong.

Walk me through a basic Dockerfile for a FastAPI app
Slim base, install deps before app code to cache layers, expose port, exec-form CMD for Uvicorn.