Consider this FastAPI endpoint using Pydantic for validation:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
quantity: int = Field(..., gt=0)
@app.post("/items/")
async def create_item(item: Item):
return {"quantity": item.quantity}What will be the response if the client sends {"quantity": 0}?
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): quantity: int = Field(..., gt=0) @app.post("/items/") async def create_item(item: Item): return {"quantity": item.quantity}
Think about how Pydantic validates fields with gt constraints.
Pydantic enforces the gt=0 constraint by rejecting values not greater than 0. FastAPI returns a 422 error with details about the validation failure.
Choose the correct Pydantic Field declaration to ensure a numeric value is at most 10.
Remember: le means less than or equal, lt means less than.
le=10 means the value can be 10 or less. lt=10 excludes 10 itself.
Examine this code snippet:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Data(BaseModel):
score: float = Field(ge=0)
@app.post("/data/")
async def post_data(data: Data):
return {"score": data.score}Why does sending {"score": null} not raise a validation error?
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Data(BaseModel): score: float = Field(ge=0) @app.post("/data/") async def post_data(data: Data): return {"score": data.score}
Check how required fields are declared in Pydantic.
Without ... as the first argument, the field is optional and defaulted to None, so validation on input is not enforced.
Given this Pydantic model:
class Product(BaseModel):
price: float = Field(..., ge=1.0, le=100.0)And this input JSON:
{"price": 100.0}What will be the value of price in the validated model instance?
from pydantic import BaseModel, Field class Product(BaseModel): price: float = Field(..., ge=1.0, le=100.0) product = Product(price=100.0) value = product.price
Check the meaning of le constraint.
le=100.0 means the value can be equal to 100.0, so 100.0 passes validation and is assigned as is.
Using Pydantic's Field constraints, which combination correctly restricts a number to be at least 5 and less than 10?
Remember: ge means greater or equal, lt means less than.
ge=5 includes 5, lt=10 excludes 10, so values are from 5 up to but not including 10.