Fastapi
211 bites tagged Fastapi — interview questions with model answers, and 60-second explainers.
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.
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.
How do you structure concurrent API calls with asyncio.gather in FastAPI?
Tests FastAPI async concurrency. Strong answer: async def endpoint with two async HTTP requests in asyncio.gather, cutting total latency from sum to max of the two. Red flag: using sync clients or threads instead of async I/O.
Write an async decorator that logs execution time for FastAPI
Use functools.wraps, wrap perf_counter around awaited call, log ms, and place decorator above path operation. Python closures, async/await, and decorator stacking in FastAPI. forgetting to await the coroutine or omitting wraps.
How does FastAPI leverage Pydantic for request validation and serialization?
This tests your understanding of FastAPI's declarative validation. Explain that type hints trigger auto-parsing, Pydantic enforces schemas and errors, and return types auto-serialize responses. Red flag: manually parsing request.body() or json.loads in routes.
What is the difference between def and async def in Python and FastAPI?
Tests event-loop boundaries: async def yields control via await for non-blocking I/O, def runs in a threadpool. Use async def only with async libraries; def covers blocking calls. Red flag: claiming async is automatically faster or awaiting inside def.
Explain Python type hints and their importance in FastAPI
Define hints as declarations; explain FastAPI uses them with Pydantic to validate requests and OpenAPI docs. If you know FastAPI uses type hints for validation and docs. Seeing hints as IDE-only.
Docker Compose for Local FastAPI Stacks
Docker Compose turns your laptop into a one-command datacenter. Define Postgres, Redis, and your FastAPI app in one YAML file and they boot as a networked stack.
Custom Field Serialization with @field_serializer
@field_serializer is an exit-only adapter for one field: it reshapes data leaving the Pydantic model without changing internals. Use it to format decimals, mask secrets, or tweak datetimes for FastAPI JSON. Never use it for validation; it only runs on output.
Per-Field Validation with @field_validator
@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.
Serialize Pydantic Models with model_dump
model_dump turns a Pydantic model into a plain Python dict, bridging typed objects and JSON serializers in FastAPI endpoints. Call it when you need raw data before returning a response. Do not confuse it with model_dump_json, which emits a string, not a dict.
FastAPI Container Build and Deploy Pipeline
Treat the Docker image as the immutable artifact: one build runs everywhere. Deploy FastAPI workers behind a load balancer, one process per container. The footgun is baking secrets into the image or running multiple processes; that breaks horizontal scaling.
Overriding FastAPI's OpenAPI Generator
FastAPI lets you swap app.openapi to reshape its generated schema without forking. Use this for vendor extensions, filtered operations, or merging external schemas. Forgetting to cache the result means every docs request rebuilds it and destroys performance.
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.
Async Path Operations in FastAPI
FastAPI path operations can be async, letting the server switch to other requests during I/O waits. Declare dependencies and sub-dependencies async when they await external calls.
Python Async Context Managers
Async context managers let you await during setup and teardown. Use async with for database connections or streams where acquiring and releasing both need I/O. The footgun is applying @contextmanager to async cleanup, which cannot await and will crash.
ARQ for FastAPI: Async Background Tasks
ARQ lets your FastAPI app offload heavy work to background workers, keeping the API responsive. It's a task queue built for asyncio. Use it for slow tasks like sending emails or processing data. The footgun is using blocking task libraries with async code.
asyncio Streams: High-Level Async Network I/O
asyncio Streams are like async file handles for the network. You get a reader/writer pair to await data, simplifying TCP clients and servers for basic protocols. The footgun: the default buffer limit is small; reading large data will fail unexpectedly.
Layered Architecture: Separating API from Business Logic
A layered architecture separates your API into distinct jobs: routing, controlling, and serving. This keeps code maintainable, like an organized toolbox. It's crucial for growing FastAPI apps.
FastAPI's StreamingResponse: Send Data in Chunks
StreamingResponse sends data piece by piece, like a live broadcast, instead of sending a complete file all at once. This keeps your server's memory low for huge responses like file downloads, video streams, or live data from AI models.
FastAPI: Validating Models with Pydantic's Field
Pydantic's `Field` adds guardrails directly to your data model's attributes. Use it to enforce constraints like string length (`max_length=50`) or numeric ranges (`gt=0`), making your models self-validating.
Mangum: Run Python ASGI Apps on Serverless
Mangum is an adapter for running Python ASGI apps (like FastAPI) on serverless platforms like AWS Lambda. It translates serverless events into ASGI requests, letting you deploy existing async web apps without a rewrite.
From Dev Server to Production: Running FastAPI with Workers
Your dev server is a single process. For production, you need a process manager to run multiple Uvicorn worker processes, handling concurrent requests and providing fault tolerance.
FastAPI's WebSocket State Machine
FastAPI manages WebSockets with a state machine, tracking client and application states separately. You must explicitly `accept()` a connection before communicating. This is key for chat or notification features.
Get Fastapi bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.