0
0
FastAPIframework~15 mins

Numeric validation (gt, lt, ge, le) in FastAPI - Deep Dive

Choose your learning style9 modes available
Overview - Numeric validation (gt, lt, ge, le)
What is it?
Numeric validation with gt, lt, ge, and le in FastAPI means checking if numbers are greater than, less than, greater or equal to, or less or equal to certain values. This helps ensure that the data your app receives fits expected rules. For example, you can require an age to be greater than 18 or a price to be less than 100. FastAPI uses these checks to automatically reject invalid data before your code runs.
Why it matters
Without numeric validation, your app might accept wrong or harmful data, causing errors or bad results. Imagine a form where users enter their age or price; if you don't check these numbers, you might get negative ages or prices that break your logic. Numeric validation keeps your app safe, reliable, and user-friendly by catching mistakes early.
Where it fits
Before learning numeric validation, you should know basic Python types and how FastAPI handles data models with Pydantic. After this, you can learn about more complex validations, custom validators, and error handling in FastAPI to build robust APIs.
Mental Model
Core Idea
Numeric validation in FastAPI uses simple rules to automatically check if numbers meet conditions like greater than or less than before your app processes them.
Think of it like...
It's like a security guard at a club entrance checking if guests meet the age limit before letting them in.
┌───────────────┐
│  Input Number │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│ Validation Rules (gt, lt, ge, le) │
└──────┬─────────────┬────────┘
       │             │
       ▼             ▼
  Passes Rules    Fails Rules
       │             │
       ▼             ▼
  Accepted       Error Response
Build-Up - 7 Steps
1
FoundationUnderstanding Basic Numeric Validation
🤔
Concept: Introduce the idea of checking if a number meets simple conditions like being greater than or less than a value.
In FastAPI, you can use Pydantic's Field function to add validation rules to numbers. For example, to require a number greater than 10, you write: from pydantic import BaseModel, Field class Item(BaseModel): value: int = Field(..., gt=10) This means the value must be greater than 10.
Result
If you try to send a value of 9, FastAPI will reject it with an error saying the value is not greater than 10.
Understanding that validation rules are simple conditions attached to data fields helps you control what data your app accepts.
2
FoundationUsing lt, ge, and le for Validation
🤔
Concept: Learn how to use less than (lt), greater or equal (ge), and less or equal (le) to set numeric limits.
Besides gt (greater than), you can use lt (less than), ge (greater or equal), and le (less or equal) in Field. For example: class Product(BaseModel): price: float = Field(..., ge=0, le=1000) This means price must be between 0 and 1000, including 0 and 1000.
Result
Sending a price of -5 or 1500 will cause FastAPI to return an error, but 0 and 1000 are accepted.
Knowing these four operators lets you precisely define numeric ranges for your data.
3
IntermediateCombining Multiple Numeric Constraints
🤔Before reading on: Do you think you can combine gt and lt together to set a range? Commit to yes or no.
Concept: You can combine multiple constraints to require a number to be within a range, like greater than 5 and less than 10.
FastAPI allows you to combine gt, lt, ge, and le in one Field. For example: class Score(BaseModel): value: int = Field(..., gt=5, lt=10) This means value must be more than 5 and less than 10.
Result
Values like 6, 7, 8, and 9 are accepted, but 5 or 10 are rejected.
Combining constraints lets you create precise numeric rules, improving data quality.
4
IntermediateAutomatic Error Messages on Validation Failure
🤔Before reading on: Do you think FastAPI returns a generic error or a detailed message when validation fails? Commit to your answer.
Concept: FastAPI automatically sends clear error messages explaining which numeric rule failed when data is invalid.
If you send a number that breaks a rule, FastAPI responds with a JSON error showing the field, the error type, and a message. For example, sending 4 to the Score model above returns: { "detail": [ { "loc": ["body", "value"], "msg": "ensure this value is greater than 5", "type": "value_error.number.gt" } ] }
Result
Users or clients see exactly why their input was rejected, making debugging easier.
Knowing FastAPI provides detailed feedback helps you design better user experiences and easier debugging.
5
AdvancedUsing Numeric Validation with Query Parameters
🤔Before reading on: Can you apply gt, lt, ge, le validation to query parameters in FastAPI? Commit to yes or no.
Concept: You can apply numeric validation not only to request bodies but also to query parameters using FastAPI's Query function.
For example, to require a query parameter 'age' greater than 18: from fastapi import FastAPI, Query app = FastAPI() @app.get("/users/") async def read_users(age: int = Query(..., gt=18)): return {"age": age} This rejects requests with age 18 or less.
Result
Requests like /users/?age=20 succeed, but /users/?age=17 return validation errors.
Applying numeric validation to query parameters extends data safety beyond request bodies.
6
AdvancedCustomizing Validation with Pydantic Validators
🤔Before reading on: Do you think built-in gt, lt, ge, le cover all numeric validation needs? Commit to yes or no.
Concept: Sometimes you need more complex numeric checks; Pydantic lets you write custom validators for this.
For example, to check a number is prime: from pydantic import BaseModel, validator class NumberModel(BaseModel): num: int @validator('num') def check_prime(cls, v): if v < 2: raise ValueError('Must be prime') for i in range(2, int(v ** 0.5) + 1): if v % i == 0: raise ValueError('Must be prime') return v This runs after basic validation.
Result
Numbers that are not prime cause validation errors with custom messages.
Knowing how to extend validation lets you handle special numeric rules beyond simple comparisons.
7
ExpertPerformance and Validation Order Considerations
🤔Before reading on: Do you think numeric validations run before or after type checks? Commit to your answer.
Concept: FastAPI and Pydantic first check data types, then apply numeric validations in order, affecting performance and error messages.
When a request arrives, Pydantic parses data to the expected type (e.g., int). If type conversion fails, numeric validations don't run. If type is correct, numeric validations like gt, lt run in the order they appear. Complex validators run last. This order means type errors are caught early, and numeric checks only run on valid types. Also, excessive or complex validations can slow response times, so keep rules simple when possible.
Result
You get clear, ordered validation errors and efficient processing.
Understanding validation order helps you write efficient, clear validation logic and interpret errors correctly.
Under the Hood
FastAPI uses Pydantic models to parse and validate incoming data. When data arrives, Pydantic first converts it to the declared type (like int or float). Then it applies validation rules like gt, lt, ge, and le by comparing the value against the limits. If any rule fails, Pydantic raises a ValidationError, which FastAPI catches and converts into a clear HTTP error response. This process happens before your endpoint code runs, ensuring only valid data reaches your logic.
Why designed this way?
This design separates data validation from business logic, making code cleaner and safer. Using Pydantic leverages Python's type hints and declarative syntax, making validation easy to write and read. The choice to validate before running endpoint code prevents wasted computation and security risks. Alternatives like manual validation are error-prone and verbose, so this automatic approach improves developer productivity and app reliability.
┌───────────────┐
│ Incoming Data │
└──────┬────────┘
       │
       ▼
┌───────────────────────┐
│ Pydantic Type Parsing │
└──────┬────────────┬───┘
       │            │
   Success         Fail
       │            │
       ▼            ▼
┌───────────────────────┐  ┌─────────────────────┐
│ Numeric Validations    │  │ ValidationError     │
│ (gt, lt, ge, le checks)│  │ (Type error)        │
└──────┬────────────┬───┘  └─────────┬───────────┘
       │            │                │
    Pass          Fail              │
       │            │                │
       ▼            ▼                │
┌───────────────┐  ┌───────────────┐  │
│ Endpoint Code │  │ Validation    │  │
│ Runs with     │  │ Error Response│  │
│ Valid Data    │  │ Sent to Client│  │
└───────────────┘  └───────────────┘  │
                                     │
                                     ▼
                            ┌─────────────────┐
                            │ Client Receives │
                            │ Error Message   │
                            └─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does gt=5 allow the value 5? Commit to yes or no.
Common Belief:If I set gt=5, the value 5 is accepted because it is equal to 5.
Tap to reveal reality
Reality:gt means strictly greater than, so 5 is NOT accepted; only values greater than 5 pass.
Why it matters:Accepting 5 when gt=5 is set breaks the intended rule and can cause logic errors or security issues.
Quick: Do you think lt and le behave the same? Commit to yes or no.
Common Belief:lt and le are the same and both include the limit value.
Tap to reveal reality
Reality:lt means less than (strictly), while le means less than or equal to (includes the limit).
Why it matters:Confusing these can cause off-by-one errors and unexpected validation failures.
Quick: Does FastAPI validate query parameters automatically with gt, lt? Commit to yes or no.
Common Belief:FastAPI only validates request bodies, not query parameters.
Tap to reveal reality
Reality:FastAPI can validate query parameters using Query with gt, lt, ge, le just like request bodies.
Why it matters:Missing validation on query parameters can let invalid data slip through, causing bugs.
Quick: Can you rely on numeric validation to check data types? Commit to yes or no.
Common Belief:Numeric validation like gt or lt also checks if the data is the correct type.
Tap to reveal reality
Reality:Type checking happens before numeric validation; if the type is wrong, numeric checks don't run.
Why it matters:Assuming numeric validation checks type can lead to confusing errors and missed type problems.
Expert Zone
1
Numeric validations run only after successful type conversion, so type errors are prioritized over value errors.
2
Combining multiple constraints can produce multiple errors, but Pydantic reports them in order, which affects debugging.
3
Custom validators run after built-in gt, lt, ge, le checks, allowing layered validation logic.
When NOT to use
Numeric validation with gt, lt, ge, le is not suitable for complex numeric rules like prime checking or divisibility; use custom Pydantic validators instead. Also, for very large data or streaming inputs, manual validation might be more efficient.
Production Patterns
In real APIs, numeric validation is used to enforce business rules like minimum order quantities, age restrictions, or price limits. It's combined with custom validators for complex rules and integrated with OpenAPI docs to inform API users about valid ranges.
Connections
Type Hinting in Python
Builds-on
Understanding Python's type hints helps grasp how FastAPI uses them to know what data types to validate with gt, lt, ge, and le.
Form Validation in Web Development
Same pattern
Numeric validation in FastAPI is like client-side form validation in websites, both aiming to catch bad input early for better user experience.
Quality Control in Manufacturing
Analogous process
Just as numeric validation checks if a number fits rules, quality control checks if products meet size or weight limits, ensuring standards are met.
Common Pitfalls
#1Using gt=5 but expecting 5 to be valid
Wrong approach:class Model(BaseModel): num: int = Field(..., gt=5) # Sending num=5 expecting success
Correct approach:class Model(BaseModel): num: int = Field(..., ge=5) # Sending num=5 is valid now
Root cause:Misunderstanding that gt means strictly greater than, not greater or equal.
#2Not validating query parameters with numeric constraints
Wrong approach:from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(age: int): return {"age": age} # No validation on age
Correct approach:from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(age: int = Query(..., gt=18)): return {"age": age}
Root cause:Assuming validation only applies to request bodies, not query parameters.
#3Combining incompatible constraints causing no valid values
Wrong approach:class Model(BaseModel): num: int = Field(..., gt=10, le=5) # No number can be >10 and <=5
Correct approach:class Model(BaseModel): num: int = Field(..., gt=5, le=10) # Valid range between 6 and 10
Root cause:Not checking if combined constraints logically allow any valid values.
Key Takeaways
Numeric validation in FastAPI uses gt, lt, ge, and le to enforce simple numeric rules automatically.
These validations run after type checks and before your endpoint code, ensuring only valid data is processed.
Combining multiple constraints lets you define precise numeric ranges for your data fields.
FastAPI provides clear error messages when validation fails, improving user and developer experience.
For complex numeric rules, use custom Pydantic validators beyond basic gt, lt, ge, and le.