Fastapi
211 bites tagged Fastapi — interview questions with model answers, and 60-second explainers.
FastAPI Lifespan: Code Before Startup, After Shutdown
FastAPI's lifespan events are "open for business" and "closing time" routines that run once before startup and after shutdown. Use them to initialize a DB pool or load a model. The footgun is putting request-specific logic here; it runs once only.
FastAPI Behind a Reverse Proxy: Fixing Docs URLs
A reverse proxy can hide the full URL from your FastAPI app, breaking OpenAPI docs. Tell your app about the proxy's path prefix by setting the `root_path` during initialization to ensure all generated URLs are correct.
Customizing FastAPI's Swagger UI Behavior
Treat FastAPI's Swagger UI as a configurable frontend, not a static page. You can customize its behavior by passing a dictionary of settings on app startup. This is useful for changing themes or pre-filling auth fields. The footgun: keys must be camelCase.
Exclude a FastAPI Endpoint from OpenAPI Docs
Hide an endpoint from your API docs by setting `include_in_schema=False`. Use this for internal or deprecated endpoints. The footgun: this only hides the endpoint from documentation; it remains fully functional and accessible if the URL is known.
FastAPI: Documenting Additional API Responses
Document every possible API response, not just the happy path. The `responses` decorator parameter lets you define alternative status codes and schemas, like a 404 error model, making your OpenAPI docs complete.
FastAPI: Configure API Metadata for Better Docs
Think of FastAPI metadata as your project's business card. It sets the title, version, and description in your auto-generated docs, making your API professional and discoverable. The main footgun is forgetting to update the version string after a release.
Testing WebSockets in FastAPI
Test a WebSocket conversation by scripting both sides. FastAPI's TestClient provides a `websocket_connect` context manager to send messages and assert responses sequentially, which is crucial for testing chats or live data feeds.
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.
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.
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.
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.
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…
FastAPI Background Tasks: Don't Make the Client Wait
FastAPI background tasks let you run slow operations, like sending an email, *after* returning a response. This keeps your API fast. The main footgun: these are fire-and-forget; a server crash means the task is lost without a real message queue.
CORSMiddleware: Unblocking Your Frontend from Your Backend
CORS is a browser security rule, not a server bug. Use FastAPI's CORSMiddleware to tell browsers which frontends (e.g., `localhost:3000`) are allowed to fetch data from your API (e.g., `localhost:8000`).
FastAPI RBAC: Using OAuth2 Scopes for Permissions
Treat OAuth2 scopes as a list of permissions. Instead of checking a user's role, you check if their token has the required scope (e.g., `items:write`) for an endpoint. FastAPI's Security dependency automates this check.
FastAPI: Fine-Grained Permissions with OAuth2 Scopes
Think of OAuth2 scopes as permissions on a keycard. A token gets you in the building, but scopes like `items:read` or `items:write` define which rooms you can enter. Use them in FastAPI to grant granular access.
API Keys: Simple Server-to-Server Authentication
An API key is a simple secret token a client sends to prove its identity, often in a request header. It's ideal for machine-to-machine communication where a user login flow is unnecessary. Footgun: Never send keys in URL query parameters.
HTTP Basic Auth: Simple but Insecure Access Control
HTTP Basic Auth is a simple gatekeeper for your API, prompting users for a username and password directly in the browser. It's useful for internal tools, but never use it over unencrypted HTTP as credentials are sent in a trivially decodable format.
OAuth2 Password Flow: Trading Credentials for a Token
The OAuth2 Password Flow trades a user's credentials for a temporary access token. It's used in trusted first-party apps, like a mobile app logging into its own backend, to avoid sending a password with every API call.
Password Hashing with Python's Passlib
Passlib turns plaintext passwords into secure, salted hashes that are safe to store. Use it in any Python app with user accounts to handle logins. The footgun: never compare hashes directly; always use the `.verify()` method to prevent timing attacks.
Beanie: Python Objects as MongoDB Documents
Beanie maps Pydantic models to MongoDB documents, letting you interact with the database using Python objects instead of raw queries. Use it in async apps like FastAPI for rapid, type-safe CRUD.
Motor: Don't Block Your Python App on MongoDB
Motor is the async bridge for Python apps to talk to MongoDB without blocking. Use it in FastAPI or other async frameworks to keep your server responsive during database queries.
SQLAlchemy 2.0: Async Without Blocking the Event Loop
SQLAlchemy 2.0 wraps its synchronous core with an async API, letting you `await` database calls without blocking your app's event loop. Use it in frameworks like FastAPI.
SQLAlchemy Engine vs. Session: The Switchboard and the Call
Think of SQLAlchemy's Engine as the database switchboard (one per app) and a Session as a single, short-lived phone call (one per request). This pattern is standard in FastAPI for managing database connections.
Get Fastapi bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.