Intermediate everything in Python & FastAPI, page 5

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

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.

asyncio Queues: Coordinating Asynchronous Tasks
An asyncio queue is a channel for coroutines to safely exchange data. It's ideal for producer-consumer patterns, like a web crawler feeding URLs to parsers. The main footgun: it's not thread-safe and must be used within a single event loop.

Coordinating Asyncio Tasks with Locks and Events
asyncio sync primitives are traffic signals for coroutines, preventing collisions over shared state. Use a Lock for exclusive access or an Event to signal multiple tasks to proceed. Footgun: these are for asyncio tasks only, not OS threads.
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.

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.
FastAPI Global Dependencies: DRY Your API Logic
A FastAPI global dependency is like a bouncer for your entire API, running a check on every request. Use it for universal concerns like API key validation. The footgun is applying logic that should only affect a subset of routes, making your API rigid.
FastAPI: Set Cookies Without Returning a Response Object
Inject a Response object into your endpoint to set cookies without manually building the whole response. Use this for session tokens while still returning data like a dict.
FastAPI: Use UploadFile for Efficient File Uploads
FastAPI handles file uploads as 'form data', giving you a streamable UploadFile object instead of a raw byte blob. Use this for endpoints like image or document submissions. The footgun is reading large files into memory instead of streaming them.

Pydantic: Configuring Models with `model_config`
Think of model_config as the settings panel for your Pydantic models, letting you change validation rules like string length or immutability. Use it to enforce global constraints or make models immutable. The footgun is using the old class Config: from V1.

Pydantic's Data Coercion: From Raw Data to Python Types
Pydantic automatically converts raw data, like strings from a JSON request, into the Python types you declare. It's how FastAPI turns a JSON body into a typed Python object.

Nested Pydantic Models: Composing Complex Data
Use a Pydantic model as a field type inside another to build complex, nested structures. This is essential for modeling JSON with sub-objects, like a user with an address.

FastAPI: Set a Response's HTTP Status Code
In FastAPI, set the success status code in the decorator, not the function. Use status_code=201 in @app.post() to signal resource creation. The common footgun is placing status_code in the function signature instead of the decorator itself.

FastAPI: Validate Parameters with Query and Path
FastAPI's Query and Path objects let you declare rich validation rules directly in your function's signature. Enforce string lengths, regex patterns, or numeric ranges on URL parameters without writing manual checks.
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