0
0
FastAPIframework~5 mins

Numeric validation (gt, lt, ge, le) in FastAPI

Choose your learning style9 modes available
Introduction

Numeric validation helps make sure numbers meet rules like being bigger or smaller than a value. This keeps data clean and safe.

When you want to accept only ages greater than 18 in a form.
When you need to limit a price to be less than 1000 in an online store.
When you want to ensure a rating is at least 1 and at most 5.
When you want to check that a quantity is not negative.
When you want to validate that a discount percentage is between 0 and 50.
Syntax
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'.

Examples
This means age must be greater than 18 (not 18 itself).
FastAPI
from pydantic import BaseModel, Field

class UserAge(BaseModel):
    age: int = Field(..., gt=18)
Price must be between 0 and 1000, including 0 and 1000.
FastAPI
from pydantic import BaseModel, Field

class Product(BaseModel):
    price: float = Field(..., ge=0, le=1000)
Score must be between 1 and 5 inclusive.
FastAPI
from pydantic import BaseModel, Field

class Rating(BaseModel):
    score: int = Field(..., ge=1, le=5)
Sample Program

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.

FastAPI
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}
OutputSuccess
Important Notes

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.

Summary

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.