Intermediate concepts in Python & FastAPI, page 2

Python's Asyncio Subprocesses: Non-Blocking Shell Commands
Run external commands without blocking your async app's event loop. asyncio.create_subprocess_shell lets you launch processes and await their results, keeping your server responsive.
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.
Alembic: Version Control for Your Database Schema
Alembic is like Git for your database schema, providing versioned, reversible changes. Use it with SQLAlchemy to evolve your database structure alongside your code. The footgun is that autogeneration can miss changes; always review generated scripts.

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

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

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.

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.
Refresh Tokens: Persistent Sessions Without Re-Authentication
A refresh token is a long-lived credential used to get a new, short-lived access token without re-authenticating. It's how apps keep you logged in for weeks. The footgun is storing it insecurely, letting attackers mint access tokens forever.
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…
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.
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.
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.

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.

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

Pydantic: Reusable Validation with Annotated Types
Pydantic's Annotated attaches validation logic directly to a type, making it reusable. Define a custom type like SquareNumber once and apply it to any model field, ensuring consistent validation without repeating code.
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.
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