tezvyn:

Python & FastAPI

Python, Django, FastAPI, Flask, async Python

245 bites

More in Python & FastAPI — page 7

Python & FastAPI2 min read

What standard and code elements power FastAPI's auto-generated API docs?

Tests whether you know FastAPI uses the OpenAPI standard and extracts metadata from Python type hints, Pydantic models, decorators, and docstrings to build interactive docs. Red flag: claiming you must manually maintain a separate schema file.

Python & FastAPI2 min read

How does FastAPI distinguish required optional and default query parameters

Tests whether you know FastAPI infers query parameter optionality from Python signature defaults. Answer: no default means required, Optional[T] = None means optional, T = value sets a default, with all three in one signature.

Python & FastAPI2 min read

What is the difference between a path parameter and a query parameter?

Tests REST API design and FastAPI binding. A strong answer states path params identify resources in the URL while query params filter after the question mark, then codes user_id in the route and q: str | None = None in the function.

How do you define and access a FastAPI path parameter?
Python & FastAPI2 min read

How do you define and access a FastAPI path parameter?

Tests FastAPI route-to-function binding. Good answer: curly-brace syntax in the decorator path, a matching typed function argument, and awareness that FastAPI auto-extracts and converts the value.

What is the purpose of @app.get("/") in FastAPI?
Python & FastAPI2 min read

What is the purpose of @app.get("/") in FastAPI?

Tests your understanding of FastAPI routing. A strong answer explains that the decorator binds an HTTP method and path to a Python function, registers it in the app's route table, and builds OpenAPI metadata.

Create a generic Pydantic BaseModel for API response wrappers
Python & FastAPI2 min read

Create a generic Pydantic BaseModel for API response wrappers

WHAT IT TESTS: Pydantic v2 generics and OpenAPI schema generation. ANSWER OUTLINE: subclass BaseModel and Generic[T]; type data as T; use ResponseWrapper[User]; note unparametrized TypeVars validate as Any.

Python & FastAPI2 min read

Implement an async database session dependency using yield for setup and teardown

This tests async resource lifecycle management in FastAPI. A strong answer uses async def, yields a session inside try, closes in finally, and injects with Depends. A red flag is omitting finally or using sync def for async I/O, which leaks connections.

How does Uvicorn use asyncio to handle thousands of concurrent connections?
Python & FastAPI2 min read

How does Uvicorn use asyncio to handle thousands of concurrent connections?

Tests async concurrency and the GIL. Great answers cover the event loop suspending coroutines at await, Uvicorn interleaving connections, and multi-process workers for parallelism. Red flag: claiming asyncio uses threads per request or bypasses the GIL.

How do you structure concurrent API calls with asyncio.gather in FastAPI?
Python & FastAPI2 min read

How do you structure concurrent API calls with asyncio.gather in FastAPI?

Tests FastAPI async concurrency. Strong answer: async def endpoint with two async HTTP requests in asyncio.gather, cutting total latency from sum to max of the two. Red flag: using sync clients or threads instead of async I/O.

Python & FastAPI2 min read

Write an async decorator that logs execution time for FastAPI

TESTS: Python closures, async/await, and decorator stacking in FastAPI. OUTLINE: use functools.wraps, wrap perf_counter around awaited call, log ms, and place decorator above path operation. RED FLAG: forgetting to await the coroutine or omitting wraps.

How does FastAPI leverage Pydantic for request validation and serialization?
Python & FastAPI2 min read

How does FastAPI leverage Pydantic for request validation and serialization?

This tests your understanding of FastAPI's declarative validation. Explain that type hints trigger auto-parsing, Pydantic enforces schemas and errors, and return types auto-serialize responses. Red flag: manually parsing request.body() or json.loads in routes.

What is the difference between def and async def in Python and FastAPI?
Python & FastAPI2 min read

What is the difference between def and async def in Python and FastAPI?

Tests event-loop boundaries: async def yields control via await for non-blocking I/O, def runs in a threadpool. Use async def only with async libraries; def covers blocking calls. Red flag: claiming async is automatically faster or awaiting inside def.

Explain Python type hints and their importance in FastAPI
Python & FastAPI2 min read

Explain Python type hints and their importance in FastAPI

WHAT IT TESTS: If you know FastAPI uses type hints for validation and docs. ANSWER OUTLINE: Define hints as declarations; explain FastAPI uses them with Pydantic to validate requests and OpenAPI docs. RED FLAG: Seeing hints as IDE-only.

Python & FastAPI2 min read

Docker Compose for Local FastAPI Stacks

Docker Compose turns your laptop into a one-command datacenter. Define Postgres, Redis, and your FastAPI app in one YAML file and they boot as a networked stack.

Python & FastAPI3 min read

Custom Field Serialization with @field_serializer

@field_serializer is an exit-only adapter for one field: it reshapes data leaving the Pydantic model without changing internals. Use it to format decimals, mask secrets, or tweak datetimes for FastAPI JSON. Never use it for validation; it only runs on output.

Python & FastAPI2 min read

Per-Field Validation with @field_validator

@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.

Python & FastAPI2 min read

Serialize Pydantic Models with model_dump

model_dump turns a Pydantic model into a plain Python dict, bridging typed objects and JSON serializers in FastAPI endpoints. Call it when you need raw data before returning a response. Do not confuse it with model_dump_json, which emits a string, not a dict.

FastAPI Container Build and Deploy Pipeline
Python & FastAPI2 min read

FastAPI Container Build and Deploy Pipeline

Treat the Docker image as the immutable artifact: one build runs everywhere. Deploy FastAPI workers behind a load balancer, one process per container. The footgun is baking secrets into the image or running multiple processes; that breaks horizontal scaling.

Python & FastAPI2 min read

Overriding FastAPI's OpenAPI Generator

FastAPI lets you swap app.openapi to reshape its generated schema without forking. Use this for vendor extensions, filtered operations, or merging external schemas. Forgetting to cache the result means every docs request rebuilds it and destroys performance.

Python & FastAPI2 min read

Testing FastAPI Lifespan Events

FastAPI lifespan events only run when TestClient is used as a context manager. Use this to test startup logic like DB pools before endpoints. Using TestClient(app) without with skips lifespan, leaving your app uninitialized and tests silently wrong.