Python
217 bites tagged Python — interview questions with model answers, and 60-second explainers.
Define a FastAPI endpoint with path and query parameters
Tests if you know FastAPI infers parameter location from the route string. Good answer: route with {item_id}, signature item_id: int, q: str | None = None, noting any param not in the path becomes a query param.
How would you use a Pydantic response_model to enforce output structure?
Tests separation of internal models from API contracts. Define a Pydantic output model with only safe fields, set it as the endpoint response_model, and let FastAPI filter and validate.
How do you define a Pydantic model and use it in FastAPI?
Subclass BaseModel with name str and age int, then type-hint the parameter with the model. Whether you use Pydantic BaseModel for request body validation in FastAPI.
Ensure end_date is after start_date in Pydantic
Tests whether you know field validators see only one value and cannot compare siblings. Use a model validator instead, which receives the full instance and can compare start_date and end_date. Red flag: a field validator referencing the other field.
Model an Order with a nested Product list in Pydantic
It tests Pydantic nested model composition. Define Product as BaseModel, then Order with products: list[Product]; Pydantic recursively coerces each dict and raises ValidationError on failure. A red flag is insisting on manual iteration.
Implement a custom validator for a single Pydantic model field
Use @field_validator as a classmethod, raise ValueError on failure, return the value. Your grasp of Pydantic v2 field validation hooks. Validating outside the model or confusing v1 @validator with v2.
Enforce positive price and SKU format using Pydantic Field without custom validators
Use Field(gt=0) for price and Field(pattern=r'^ITEM-\d{5}$') for SKU; mention Annotated. Pydantic V2 Field constraints vs custom validators. Suggesting @field_validator or conint/constr.
What is the difference between a Pydantic default and Optional field?
Both forms are non-required; str = 'guest' rejects None, Optional[str] = None accepts it. Separation of type constraints from requiredness.
How does Pydantic handle extra JSON fields, and how to configure it?
This tests Pydantic's data filtering behavior and configuration. By default, Pydantic ignores extra fields silently. Set model_config = ConfigDict(extra='forbid' or 'allow') to change it. A red flag is claiming FastAPI 422s by default on unknown fields.
How do you define a Pydantic model for FastAPI request body validation?
Subclass BaseModel with id int, email str, full_name str|None; pass it as a route param so FastAPI validates JSON and returns 422s. Schema validation via Python type hints. Saying manual request.json() parsing.
How do you type-hint repeated query params in FastAPI?
Tests FastAPI's Annotated pattern for multi-value query strings. A great answer uses Annotated[list[str], Query()] = [] to collect repeated keys, and notes the old Query-as-default alternative. Red flag: manual parsing or typing it as str.
FastAPI non-integer query param default behavior
Tests FastAPI's automatic Pydantic validation and default error contracts. Strong answer: 422 Unprocessable Entity with JSON detail array containing loc, msg, and type fields. Red flag: saying 400 Bad Request or manual validation is needed.
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.
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.
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?
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?
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.
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?
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?
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.
Write an async decorator that logs execution time for FastAPI
Use functools.wraps, wrap perf_counter around awaited call, log ms, and place decorator above path operation. Python closures, async/await, and decorator stacking in FastAPI. forgetting to await the coroutine or omitting wraps.
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?
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
Define hints as declarations; explain FastAPI uses them with Pydantic to validate requests and OpenAPI docs. If you know FastAPI uses type hints for validation and docs. Seeing hints as IDE-only.
Get Python bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.