More in Python & FastAPI — page 6
Access raw request bytes in FastAPI for webhook verification
Tests FastAPI's Starlette integration and stream semantics. Outline: inject Request and await request.body, but the stream is single-use so JSON parsing later fails and docs are lost. Red flag: suggesting a Pydantic model still works after consuming the body.
How would you use BackgroundTasks to run work after returning a 201?
What it tests: FastAPI deferred execution and failure modes. A strong answer injects BackgroundTasks, adds the task, returns 201, and notes same-process post-response execution with no persistence. Red flag: Treating it as a distributed queue like Celery.
Implement a custom exception handler to catch ItemNotFoundError and return 404
Tests FastAPI exception handler registration beyond HTTPException. A strong answer covers creating a custom exception, using app.exception_handler, and returning a JSONResponse with status 404 and a structured body. Red flag: per-route try/except, plain dict.
How do you set a custom header and cookie in FastAPI?
Tests FastAPI temporal Response injection and merge behavior. Strong answer: inject Response, set headers via response.headers, cookies via set_cookie, then return the payload normally.
How do you create a reusable current-user dependency in FastAPI?
Tests DRY auth with FastAPI Depends. Answer: create get_current_user that Depends on OAuth2PasswordBearer, verifies token, returns User model, inject into routes. Red flag: middleware or manual header parsing in each endpoint.
Implement a FastAPI file upload endpoint with form data
Tests FastAPI multipart literacy. A strong answer names python-multipart, uses Annotated[UploadFile, File()] for the image, and Annotated[str, Form()] for user_id.
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?
WHAT IT TESTS: Whether you use Pydantic BaseModel for request body validation in FastAPI. ANSWER OUTLINE: Subclass BaseModel with name str and age int, then type-hint the parameter with the model.

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.