More in Backend Dev — page 22

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.

How do you prevent password_hash from appearing in a FastAPI response?
Tests FastAPI response filtering and the security practice of separating DB schemas from API contracts. A strong answer proposes a dedicated output model omitting the field, then cites response_model_exclude. Red flag: manual dict deletion or monkey-patching.

Implement a custom validator for a single Pydantic model field
WHAT IT TESTS: Your grasp of Pydantic v2 field validation hooks. ANSWER OUTLINE: Use @field_validator as a classmethod, raise ValueError on failure, return the value. RED FLAG: Validating outside the model or confusing v1 @validator with v2.

Enforce positive price and SKU format using Pydantic Field without custom validators
WHAT IT TESTS: Pydantic V2 Field constraints vs custom validators. ANSWER OUTLINE: Use Field(gt=0) for price and Field(pattern=r'^ITEM-\d{5}$') for SKU; mention Annotated. RED FLAG: Suggesting @field_validator or conint/constr.

What is the difference between a Pydantic default and Optional field?
WHAT IT TESTS: Separation of type constraints from requiredness. ANSWER OUTLINE: Both forms are non-required; str = 'guest' rejects None, Optional[str] = None accepts it.

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?
WHAT IT TESTS: Schema validation via Python type hints. ANSWER OUTLINE: Subclass BaseModel with id int, email str, full_name str|None; pass it as a route param so FastAPI validates JSON and returns 422s. RED FLAG: Saying manual request.json() parsing.

What is the :path converter in FastAPI?
Tests FastAPI routing semantics and URL segmentation. A strong answer states :path captures slashes across segments while plain str stops at the next slash, and cites file-serving as the use case.

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.

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.
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.