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

FastAPI Response Models: Shape Your API's Output
A FastAPI response_model defines your API's output shape, acting as a data filter and automatic documentation generator. Use it to prevent data leaks and provide clear schemas.

Implement a custom validator for a single Pydantic model field
Use @field_validator as a classmethod, raise ValueError on failure, return the value.

FastAPI: Automatic Interactive API Docs
FastAPI turns your Python type hints into live, interactive API documentation. It generates an OpenAPI schema to power a UI where you can test endpoints directly from your browser, no extra work needed.

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.

FastAPI: Validate Parameters with Query and Path
FastAPI's Query and Path objects let you declare rich validation rules directly in your function's signature. Enforce string lengths, regex patterns, or numeric ranges on URL parameters without writing manual checks.

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.

FastAPI: Set a Response's HTTP Status Code
In FastAPI, set the success status code in the decorator, not the function. Use status_code=201 in @app.post() to signal resource creation. The common footgun is placing status_code in the function signature instead of the decorator itself.

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.
FastAPI: Use HTTPException to Return Client Errors
FastAPI's HTTPException is your tool for stopping an operation and sending a clean HTTP error. Raise it when business logic fails, like a missing database record. The footgun is catching it yourself; just raise it and let FastAPI do the rest.

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.

Async Path Operations in FastAPI
FastAPI path operations can be async, letting the server switch to other requests during I/O waits. Declare dependencies and sub-dependencies async when they await external calls.

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.
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.
Starlette's Request Object: A Clean API for ASGI
Starlette's Request object is a high-level wrapper around the raw ASGI scope, providing a clean API for request data. Use it in endpoints to read headers, query params, or parse the body. The footgun: the request body can only be read once.
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.

Pydantic: Required vs. Optional Fields
In Pydantic, a field is required by default. To make it optional, you must provide a default value, like name: str = "guest" or age: int | None = None. This is key for flexible API request bodies.
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.

Nested Pydantic Models: Composing Complex Data
Use a Pydantic model as a field type inside another to build complex, nested structures. This is essential for modeling JSON with sub-objects, like a user with an address.
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.

Pydantic's Data Coercion: From Raw Data to Python Types
Pydantic automatically converts raw data, like strings from a JSON request, into the Python types you declare. It's how FastAPI turns a JSON body into a typed Python object.