Numeric validation helps make sure numbers meet rules like being bigger or smaller than a value. This keeps data clean and safe.
Numeric validation (gt, lt, ge, le) in FastAPI
from pydantic import BaseModel, Field class Item(BaseModel): price: float = Field(..., gt=0, lt=100) quantity: int = Field(..., ge=1, le=10)
Use gt for 'greater than', lt for 'less than'.
Use ge for 'greater or equal', le for 'less or equal'.
from pydantic import BaseModel, Field class UserAge(BaseModel): age: int = Field(..., gt=18)
from pydantic import BaseModel, Field class Product(BaseModel): price: float = Field(..., ge=0, le=1000)
from pydantic import BaseModel, Field class Rating(BaseModel): score: int = Field(..., ge=1, le=5)
This FastAPI app defines an Item model with numeric validation rules. The price must be greater than 0 and less than 100. The quantity must be between 1 and 10 inclusive. If invalid data is sent, FastAPI returns a clear error message.
from fastapi import FastAPI, Request from pydantic import BaseModel, Field from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError app = FastAPI() class Item(BaseModel): price: float = Field(..., gt=0, lt=100) quantity: int = Field(..., ge=1, le=10) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={"detail": exc.errors(), "body": exc.body}, ) @app.post("/items/") async def create_item(item: Item): return {"price": item.price, "quantity": item.quantity}
Validation errors automatically return HTTP 422 with details.
Use Field(...) to mark fields as required with validation.
These validations happen before your code runs, so you get clean data.
Numeric validation ensures numbers meet rules like greater than or less than.
Use gt, lt, ge, and le in Pydantic Field to set these rules.
FastAPI uses these validations automatically to protect your app from bad data.
Practice
Field to ensure a number is strictly greater than 10?Solution
Step 1: Understand the meaning of
Thegtgtparameter means "greater than" and excludes the value itself.Step 2: Match the requirement
Since the question asks for strictly greater than 10,gt=10is the correct choice.Final Answer:
gt=10-> Option AQuick Check:
Strictly greater than 10 = gt=10 [OK]
- Confusing gt with ge and using ge=10 instead
- Using lt or le which mean less than
- Thinking gt includes the number 10
Solution
Step 1: Identify the parameter for less than or equal
The parameterlestands for "less than or equal to".Step 2: Check the syntax
The correct syntax isField(le=100)to enforce the value to be at most 100.Final Answer:
Field(le=100) -> Option CQuick Check:
Less than or equal to 100 = le=100 [OK]
- Using lt=100 which excludes 100
- Using ge or gt which are for greater values
- Writing Field(le100) without equals sign
from pydantic import BaseModel, Field
class Item(BaseModel):
price: float = Field(gt=0, le=100)What happens if you send a request with
price=0?Solution
Step 1: Analyze the validation rules
The field hasgt=0(greater than 0) andle=100(less or equal to 100).Step 2: Check the input value
Input price is 0, which is not greater than 0, so it violates thegt=0rule.Final Answer:
Validation error because price must be greater than 0 -> Option DQuick Check:
Price 0 fails gt=0 validation [OK]
- Thinking 0 passes because it is less than 100
- Confusing gt with ge and allowing 0
- Ignoring validation errors in FastAPI
from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(ge=18, lt=65)But when you send
age=65, it passes validation. Why?Solution
Step 1: Understand the meaning of
ltandlelt=65means strictly less than 65, so 65 should fail validation.Step 2: Identify the cause of passing validation
If 65 passes, likely the code usesle=65(less or equal) instead oflt=65, allowing 65.Final Answer:
Becauselt=65means less than 65, so 65 should fail but it passes because you usedle=65instead oflt=65-> Option AQuick Check:
lt excludes value; le includes it [OK]
- Confusing lt and le parameters
- Assuming validation is not enforced on integers
- Thinking ge affects upper bound
Solution
Step 1: Understand inclusive range requirements
Inclusive means the value can be equal to the limits, so usege(greater or equal) andle(less or equal).Step 2: Match parameters to the range 1 to 5 inclusive
Usege=1andle=5to allow 1 and 5 as valid values.Final Answer:
rating: int = Field(ge=1, le=5) -> Option BQuick Check:
Inclusive range uses ge and le [OK]
- Using gt or lt excludes boundary values
- Mixing gt with le or ge with lt incorrectly
- Forgetting to include both bounds
Ready to prove it?
Pass the test and this pattern moves unknown
