Skip to content
tezvyn:

All bites

The whole library, newest first. Filter by what you are here for, or pick a topic if you already know.

4330 bites

Page 2

Enforce positive price and SKU format using Pydantic Field without custom validators
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.

Implement a custom validator for a single Pydantic model field
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.

How do you prevent password_hash from appearing in a FastAPI response?
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.

Model an Order with a nested Product list in Pydantic
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.

Ensure end_date is after start_date in Pydantic
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.

How do you define a Pydantic model and use it in FastAPI?
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.

How would you use a Pydantic response_model to enforce output structure?
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

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

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

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

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

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

Python & FastAPI2 min read

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 do you declare a function as a dependency, and why?
Python & FastAPI2 min read

How do you declare a function as a dependency, and why?

Tests FastAPI dependency injection basics. Answer: create a function, import Depends, and add it to path operation parameters so FastAPI injects it. Purpose: routes declare what they need instead of hard-coding shared logic.

Python & FastAPI2 min read

What is the purpose of yield in a dependency function?

Tests teardown logic in FastAPI dependencies. Yield splits setup from cleanup: code before yield runs pre-request, after yield runs post-response to close resources like DB sessions. Red flag: confusing it with return or thinking yield is only for generators.

Python & FastAPI2 min read

How do you apply a dependency to an APIRouter without per-endpoint signatures?

Pass Depends() to APIRouter dependencies parameter; runs before every route in that router and shows in docs.

Python & FastAPI2 min read

How would you override a FastAPI dependency during testing?

Tests your grasp of FastAPI's dependency override mechanism. A strong answer mentions app.dependency_overrides, notes that sub-dependencies are bypassed, and stresses clearing overrides after each test.

How do you use a Python class as a FastAPI dependency?
Python & FastAPI2 min read

How do you use a Python class as a FastAPI dependency?

It tests whether you understand FastAPI DI beyond functions and when stateful encapsulation wins. Explain that Depends takes callable classes, centralizing setup and shared state in __init__. Red flag: claiming classes are pure syntactic sugar.

Python & FastAPI2 min read

How does FastAPI execute setup and teardown in nested yield dependencies?

It tests FastAPI's dependency injection lifecycle and stack-like teardown for nested yield dependencies. Setup runs top-down; teardown runs bottom-up after the response. A red flag is claiming teardown order is arbitrary or follows garbage collection.