Skip to content
tezvyn:

Fastapi

211 bites tagged Fastapi — interview questions with model answers, and 60-second explainers.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI1 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

Python & FastAPI2 min read

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.

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.

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.

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.

Python & FastAPI2 min read

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.