Fastapi
211 bites tagged Fastapi — interview questions with model answers, and 60-second explainers.
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.
Pydantic: Required vs. Optional Fields
In Pydantic, a field is required by default. To make it optional, you must provide a default value, like `name: str = "guest"` or `age: int | None = None`. This is key for flexible API request bodies.
Starlette's Request Object: A Clean API for ASGI
Starlette's Request object is a high-level wrapper around the raw ASGI scope, providing a clean API for request data. Use it in endpoints to read headers, query params, or parse the body. The footgun: the request body can only be read once.
FastAPI: Use HTTPException to Return Client Errors
FastAPI's HTTPException is your tool for stopping an operation and sending a clean HTTP error. Raise it when business logic fails, like a missing database record. The footgun is catching it yourself; just `raise` it and let FastAPI do the rest.
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.
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 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 Type Hints: Documentation Your Linter Can Read
Type hints are labels for variables and function returns (`name: str`) that Python ignores at runtime. They enable static analysis tools and IDEs to catch errors before you run code.
Get Fastapi bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.