More in Python & FastAPI — page 12

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.

FastAPI: Automatic Interactive API Docs
FastAPI turns your Python type hints into live, interactive API documentation. It generates an OpenAPI schema to power a UI where you can test endpoints directly from your browser, no extra work needed.

FastAPI Response Models: Shape Your API's Output
A FastAPI `response_model` defines your API's output shape, acting as a data filter and automatic documentation generator. Use it to prevent data leaks and provide clear schemas.

FastAPI: Pydantic for Robust Request Bodies
A Pydantic model is a contract for your API's request body. It tells FastAPI what data to expect, automatically converting incoming JSON into a typed Python object. Use this for any POST or PUT endpoint. The footgun is declaring path params in the body model.
Uvicorn Workers: Scaling Your FastAPI App
Uvicorn workers are like adding cashiers to a store. Instead of one process handling all requests, you run multiple, letting your FastAPI app use all CPU cores to serve more users concurrently.
FastAPI Query Parameters: Beyond the URL Path
In FastAPI, function arguments not in the URL path become query parameters—the optional key-value pairs after a URL's `?`. Use them for filtering or pagination, like `/items?skip=0&limit=10`. The footgun: omitting a default value makes the parameter required.

Path Parameters: Turning URL Parts into Variables
Path parameters turn parts of a URL, like `/users/123`, into typed function arguments. FastAPI uses this to create endpoints for specific resources, like fetching a user by their ID. The footgun is forgetting type hints; without `int`, `123` is just a string.

FastAPI: Configure Endpoints with Decorators
FastAPI's path operation decorators configure an endpoint's metadata and behavior. Use them to set status codes (status_code=201), group endpoints with `tags`, or mark them as `deprecated`.

FastAPI Application Instance: Your API's Central Hub
The FastAPI instance is your API's central switchboard, connecting incoming requests to your code. You create it once (e.g., `app = FastAPI()`) and use its decorators like `@app.get` to define all your endpoints. The footgun is creating multiple instances.

The Python GIL: One Thread at a Time
The Python Global Interpreter Lock (GIL) is a mutex ensuring only one thread executes Python bytecode at a time. This serializes CPU-bound threads, but the lock is released during I/O, making it effective for network-bound tasks.

Python Concurrency vs. Parallelism
Concurrency is juggling tasks; parallelism is doing them at once. In Python, use concurrency (threading/asyncio) for I/O-bound work like API calls, and parallelism (multiprocessing) for CPU-bound tasks.

Accessing Python Type Annotations Safely
Accessing an object's type hints isn't just `obj.__annotations__`. Use `inspect.get_annotations()` in Python 3.10+ for safe access. This is key for tools like FastAPI that introspect your code.

Python's async/await: Concurrent, Not Parallel
async/await lets a single Python thread juggle multiple tasks, pausing one to work on another while it waits for I/O. It's ideal for network requests or database queries. The footgun: it won't speed up CPU-bound tasks, it only helps with waiting.

Python Coroutines: Functions You Can Pause and Resume
A Python coroutine is a function that can be paused and resumed. It yields control during I/O waits, allowing other tasks to run instead of blocking the program. The main footgun: calling an `async` function does nothing; you must `await` it to run it.

The `with` Statement: Python's Automatic Cleanup Crew
A context manager is Python's automatic cleanup crew. It uses the `with` statement to guarantee setup and teardown code runs, even if errors occur. It's essential for files and database connections.

Python's `yield`: Functions That Pause and Resume
Python's `yield` creates a generator: a pausable function that produces values on-demand, saving memory. Use it for large files or infinite sequences. The footgun: a generator is a one-time-use iterator; you can't loop over it twice.

Python Decorators: Functions that Wrap Functions
A decorator is a function that wraps another function, adding behavior without modifying the original code. They're used for caching, logging, or access control. The main footgun is forgetting that decorators run at definition time, not call time.

Python Enums: Give Names to Magic Numbers
Python's Enum gives meaningful names to "magic numbers" or strings. Use it for fixed sets of options like statuses or categories to make code self-documenting. The footgun: don't compare members to raw values; compare member to member for type safety.

Python Packages: Grouping Modules with __init__.py
A Python package is a folder of modules treated as one unit. The `__init__.py` file marks the folder as a package and can run setup code. Use it to organize large codebases.