Fastapi
211 bites tagged Fastapi — interview questions with model answers, and 60-second explainers.
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?
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.
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
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.
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
Subclass BaseModel and Generic[T]; type data as T; use ResponseWrapper[User]; note unparametrized TypeVars validate as Any. Pydantic v2 generics and OpenAPI schema generation.
Get Fastapi bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.