Python
217 bites tagged Python — interview questions with model answers, and 60-second explainers.
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.
FastAPI: Returning HTML with HTMLResponse
Override FastAPI's default JSON output by using `HTMLResponse` to return a raw HTML string directly from an endpoint. It's for simple status pages or server-side rendered components.
FastAPI: Reading Request Cookies
FastAPI treats request cookies like any other parameter. Declare them directly in your endpoint's function signature using `Cookie()`, and the framework will extract the value for you. Use this for reading session IDs or user preferences.
Declaring Request Headers in FastAPI
Treat request headers like any other parameter in FastAPI. Declare them in your function signature to access values like `User-Agent` or `X-Token`. FastAPI automatically converts hyphens to underscores, so `User-Agent` is accessed via the `user_agent`…
FastAPI: Handling Form Data, Not Just JSON
FastAPI can handle classic HTML form data, not just JSON. Use `Form` to define expected fields in your endpoint, just like query parameters. It's ideal for login pages. The footgun: forgetting to `pip install python-multipart` will break form parsing.
Pydantic Computed Fields: Serialize Derived Values
A Pydantic computed field makes a derived value, like an area from width and length, part of your model's serialized output. Use it to include calculated attributes when calling `.model_dump()`.
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.
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.
Get Python bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.