new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

FastAPI · all subjects

pydantic & validation

7 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Pydantic BaseModel for request bodies

Request body models are declared by creating a class that inherits from pydantic.BaseModel with type-annotated attributes. Example: class Item(BaseModel): name: str; price: float; is_offer: bool | None = None. Optional fields use | None = None syntax.

Numeric validation operators for Path parameters

Path parameters support numeric validation using the following operators: gt (greater than), ge (greater than or equal), lt (less than), le (less than or equal). These work for both integer and float values.

Use gt and lt for strict numeric bounds on floats

For float values, gt (greater than) and lt (less than) are important to enforce strict bounds. For example, gt=0 forces a value greater than 0 even if less than 1, so 0.5 is valid but 0.0 or 0 is not.

Pydantic powers path parameter validation

All data validation for path parameters is performed by Pydantic behind the scenes. You can use the same type declarations with `str`, `float`, `bool`, and many other complex data types.

Forbid extra form fields with Pydantic config

To forbid extra fields in a Pydantic model used for form request bodies, use Pydantic's model configuration to set extra='forbid'. This will cause an error response if a client attempts to send additional fields not declared in the model. The error response includes type 'extra_forbidden' with location ['body', 'fieldname'] and message 'Extra inputs are not permitted'.

Forbid extra fields supported since FastAPI 0.114.0

The ability to forbid extra form fields on Pydantic models is supported starting from FastAPI version 0.114.0.

Extra forbidden error response format

When extra fields are forbidden and a client sends additional data, the error response is a JSON array with objects containing: 'type': 'extra_forbidden', 'loc': ['body', 'fieldname'], 'msg': 'Extra inputs are not permitted', 'input': <value>. The entire response is wrapped in a 'detail' key.

Give your agent this brain