Skip to content
tezvyn:

Fastapi

211 bites tagged Fastapi — interview questions with model answers, and 60-second explainers.

Python & FastAPI2 min read

Async Generators: `yield` in an `async` World

Async generators let you write I/O-bound data streams with the elegance of `yield`. An `async def` function with `yield` produces values one at a time, pausing for I/O without blocking. This is ideal for streaming data from a database.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

The asyncio Event Loop: One Thread, Many Tasks

The asyncio event loop is a manager for a single-threaded process, juggling tasks to prevent idleness during slow I/O. It's the core of apps like FastAPI, handling network requests efficiently. The footgun is interacting with it directly; use `asyncio.run()`.

Python & FastAPI2 min read

FastAPI: Mounting Independent Sub-Applications

Mounting delegates a URL prefix to a separate FastAPI app, giving it its own isolated logic and API docs. Use it to combine microservices or isolate domains. The footgun: the main app's dependencies and middleware do not apply to the sub-app.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI1 min read

FastAPI: Splitting Your App with `include_router`

`app.include_router` is like plugging a pre-wired power strip of API endpoints into your main FastAPI app. It lets you organize a large app into smaller files by feature, then combine them. The footgun is forgetting to add a URL `prefix` for each router.

Python & FastAPI2 min read

FastAPI's APIRouter: Grouping Routes into Modules

Think of APIRouter as a mini-FastAPI app for organizing endpoints. It lets you group related paths, like all user routes, into a separate file. This is crucial for keeping large applications maintainable.

Python & FastAPI1 min read

Accessing the Raw Request Object in FastAPI

Think of it as dropping to a lower level. Instead of FastAPI handing you validated data, you grab the raw Starlette HTTP request yourself. Use this for data not covered by standard declarations, like a client's IP.

Python & FastAPI2 min read

Overriding FastAPI Dependencies for Testing

Overriding dependencies lets you swap real components for fakes during tests. This is vital for isolating tests from external services like auth providers or databases, letting you control inputs and avoid slow, flaky network calls.

Python & FastAPI2 min read

FastAPI's Security Utility: Dependencies for Auth

FastAPI's `Security` utility is a specialized `Depends` for authentication. It signals to OpenAPI that a dependency is required for security, enabling interactive docs. Use it to protect endpoints by injecting the authenticated user.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

FastAPI's Dependency Caching: One Request, One Call

FastAPI dependencies are singletons for the life of a request. If multiple parts of your code ask for the same dependency (e.g., a database session), FastAPI runs it once, caches the result, and shares it. The footgun: this cache is per-request, not global.

Python & FastAPI2 min read

FastAPI: Using Classes as Dependencies

Bundle related request parameters into a class instead of repeating them in every endpoint. FastAPI automatically creates an instance for you, cleaning up your code. This is ideal for shared logic like pagination. The footgun: FastAPI injects into `__init__`.

Python & FastAPI2 min read

FastAPI's Depends: Let the Framework Handle Setup

Think of `Depends` as a pre-flight checklist for your API endpoints. You list required setup tasks, like getting a user or a database session, and FastAPI runs them for you. This is key for sharing logic like auth or database connections across many routes.

Python & FastAPI2 min read

FastAPI: Setting Custom Response Headers

Set custom HTTP headers in FastAPI by adding a `Response` parameter to your endpoint. This lets you add metadata like trace IDs without changing your return data. The footgun is thinking you must return the `Response` object; just return your data as usual.

Python & FastAPI2 min read

FastAPI `yield` Dependencies for Setup and Teardown

A `yield` dependency is a context manager for your endpoints. Code before `yield` runs setup, like getting a DB connection; code after `yield` runs teardown.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI1 min read

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.

Python & FastAPI1 min read

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`…

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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()`.

Get Fastapi bites daily.

Five a day, five minutes, offline. With quizzes so it sticks.

Open testing — you’ll join as an early tester.