
When building a backend application, one thing becomes clear pretty quickly: receiving data is easy, but trusting that data is a different story.
Imagine you're building a REST API for an e-commerce application. A client sends a request to create an order with a customer ID, a list of products, quantities, shipping information, and a payment method. Everything looks fine at first, but what happens if the quantity is negative, the email address is invalid, or the shipping address is missing a required field?
You could write separate validation checks for every field inside your API endpoints. That works for small applications, but as the project grows, the same validation logic starts appearing in multiple places.
This is where Pydantic becomes useful.
Pydantic allows us to define the structure of our data using Python type hints and validate incoming values against that structure. It also supports custom validation rules, nested models, serialization, and settings management through environment variables.
With Pydantic v2, the validation and serialization architecture was redesigned, making it a strong choice for modern Python applications, particularly when working with FastAPI.
In this guide, we'll explore Pydantic beyond basic field validation. We'll build practical examples, handle complex request payloads, validate related fields, manage application settings, and discuss mistakes that can cause problems in production.
1. What Is Pydantic and Why Do We Need It?
Python is dynamically typed, which means that you don't normally have to declare the type of a variable before assigning a value to it.
For example:
user_id = 101
user_name = "Manjeet"
is_active = TruePython allows these assignments without requiring a schema.
That flexibility is useful, but API requests and external data sources introduce a different challenge. Data received from a client, a database, a configuration file, or a third-party service might not match what your application expects.
Consider this request:
{
"name": "Mechanical Keyboard",
"price": "2499.99",
"quantity": "2"
}The client has sent the price and quantity as strings instead of JSON numbers.
Should the application accept these values? Should it reject them? Should it convert them?
The answer depends on your application's data contract.
Without a validation layer, you may end up writing checks throughout the codebase:
def create_product(data):
name = data.get("name")
price = data.get("price")
quantity = data.get("quantity")
if not name:
raise ValueError("Product name is required")
try:
price = float(price)
except (TypeError, ValueError):
raise ValueError("Invalid price")
try:
quantity = int(quantity)
except (TypeError, ValueError):
raise ValueError("Invalid quantity")
return {
"name": name,
"price": price,
"quantity": quantity,
}This example is manageable, but a real application might have dozens of fields, nested objects, optional properties, and rules that depend on multiple values.
Pydantic lets us express these rules through models instead.
Install Pydantic v2:
pip install "pydantic>=2.0,<3.0"For a production application, select and lock a tested version rather than relying on a broad version range.
Now create a model:
from pydantic import BaseModel, Field
class ProductCreate(BaseModel):
name: str = Field(min_length=3, max_length=150)
price: float = Field(gt=0, allow_inf_nan=False)
quantity: int = Field(ge=1)
product = ProductCreate(
name="Mechanical Keyboard",
price=2499.99,
quantity=2,
)
print(product.name)
print(product.price)
print(product.quantity)Pydantic validates the input against the model definition and produces a structured Python object.
If the price is zero or negative, validation fails. If the product name is too short, Pydantic raises a validation error.
One important detail: Pydantic can coerce certain inputs into the expected types by default. If your application requires strict type checking, you can configure strict validation instead.
This distinction becomes important when designing APIs that need a precise contract.
2. Understanding Pydantic v2's Validation Flow
Before moving into advanced validation, it helps to understand what happens when a Pydantic model receives data.
Consider:
from pydantic import BaseModel, Field
class UserCreate(BaseModel):
name: str = Field(min_length=2)
age: int = Field(ge=18)
user = UserCreate(
name="Alex",
age=25,
)Pydantic processes the supplied values, validates them against the model schema, and returns an instance if validation succeeds.
If validation fails, it raises a ValidationError containing details about the invalid fields.
For example:
from pydantic import ValidationError
try:
UserCreate(
name="A",
age=16,
)
except ValidationError as error:
print(error.errors())The returned errors contain information such as the location of the invalid value, the error type, and a message describing the validation failure.
This is useful when building APIs because you can return structured feedback to the client instead of manually checking every field.
Pydantic v2 uses pydantic-core for much of its validation and serialization work. This provides an efficient validation engine, although actual performance still depends on the model structure, data size, and complexity of your custom validators.
The goal should be to define clear validation rules rather than assuming that using a particular library automatically makes every application faster.
3. Using Field Constraints for Better Validation
The simplest way to improve validation is to define constraints directly on your fields.
Pydantic's Field() function supports constraints for numbers, strings, collections, and other values.
Let's create a more complete product model:
from pydantic import BaseModel, Field
class ProductCreate(BaseModel):
name: str = Field(
min_length=3,
max_length=150,
)
price: float = Field(
gt=0,
allow_inf_nan=False,
)
quantity: int = Field(
ge=1,
le=10000,
)
description: str | None = Field(
default=None,
max_length=1000,
)Here is what these constraints mean:
Constraint | Meaning |
|---|---|
| Requires at least three characters |
| Limits the length of a string |
| Requires a value greater than zero |
| Requires a value greater than or equal to one |
| Sets an upper bound |
| Rejects infinity and NaN for supported numeric fields |
These rules make the model easier to understand because the expected data structure and its constraints are defined together.
Be careful with numeric types
For quantities, an integer is usually appropriate.
For money, however, float can introduce precision problems because many decimal fractions cannot be represented exactly in binary floating-point.
For example, a financial application may be better served by Decimal:
from decimal import Decimal
from pydantic import BaseModel, Field
class PaymentRequest(BaseModel):
amount: Decimal = Field(
gt=Decimal("0"),
max_digits=12,
decimal_places=2,
)This is a more suitable starting point for financial values, although the database column type, currency rules, rounding behavior, and serialization format must also be designed carefully.
A useful rule: Choose the data type based on what the value represents, not simply on which type is easiest to use.
4. Custom Field Validation with field_validator
Built-in constraints cover many situations, but some business rules require custom logic.
Suppose you're building a user registration endpoint. You want to accept an email address and a username, but usernames must follow specific rules.
For example:
The username must contain at least three characters.
Only letters, numbers, and underscores are allowed.
The username must not contain spaces.
You can use field_validator to define this behavior.
import re
from pydantic import BaseModel, EmailStr, field_validator
class UserCreate(BaseModel):
username: str
email: EmailStr
@field_validator("username")
@classmethod
def validate_username(cls, value: str) -> str:
value = value.strip()
if len(value) < 3:
raise ValueError(
"Username must contain at least 3 characters"
)
if not re.fullmatch(r"[A-Za-z0-9_]+", value):
raise ValueError(
"Username can contain only letters, numbers, and underscores"
)
return valueInstall the email validation dependency:
pip install email-validatorThe EmailStr type performs email-format validation. It does not prove that the address exists or that the person submitting it owns the address.
For ownership verification, you would normally send a verification email containing a short-lived token.
Why return the value?
Notice that the validator returns the cleaned username:
return valueA field validator can transform the input as part of validation. Here, leading and trailing whitespace is removed before the value is stored on the model.
If the input violates a rule, raising ValueError tells Pydantic that validation has failed.
Pydantic then includes the error in its ValidationError.
This is generally preferable to manually raising a Pydantic ValidationError inside your validator.
Why use @classmethod?
Pydantic v2's recommended validator pattern uses @field_validator with a class method.
The validator receives the value being processed and can return the validated or transformed result.
Keep validators focused. If a validator starts performing database queries, calling external services, or implementing complicated business workflows, that logic probably belongs in a service layer instead.
5. Validating Relationships Between Fields
Some validation rules depend on more than one field.
Imagine an online store that supports discounts. A discount must have a start date and an end date, and the end date cannot be earlier than the start date.
Validating each date independently won't enforce that relationship.
Pydantic v2 provides model_validator for validation involving the entire model.
from datetime import datetime
from pydantic import BaseModel, model_validator
class DiscountCreate(BaseModel):
name: str
starts_at: datetime
ends_at: datetime
@model_validator(mode="after")
def validate_date_range(self):
if self.ends_at <= self.starts_at:
raise ValueError(
"End date must be later than start date"
)
return selfNow this model validates the relationship between the two dates.
from datetime import datetime
discount = DiscountCreate(
name="Summer Sale",
starts_at=datetime(2026, 6, 1, 0, 0),
ends_at=datetime(2026, 6, 30, 23, 59),
)If the end date is earlier than the start date, validation fails.
Why use mode="after"?
An after-model validator runs after the model's fields have been validated.
This means you can access the validated values through self.
Pydantic v2 also supports before-model validators, which run before the input is processed into the model's field values.
Before validators are useful when you need to normalize or reshape incoming data before normal field validation takes place.
However, before validators should be used carefully because the input may be a dictionary, an existing model instance, or another supported input representation depending on how validation is invoked.
A real-world use case: password confirmation
The same pattern can validate password confirmation during registration.
from pydantic import BaseModel, Field, model_validator
class RegisterRequest(BaseModel):
password: str = Field(min_length=12)
confirm_password: str
@model_validator(mode="after")
def validate_passwords(self):
if self.password != self.confirm_password:
raise ValueError("Passwords do not match")
return selfThis ensures the two supplied values match.
Remember that this only checks equality and length. It does not hash the password or establish that the password is safe against every possible attack.
Passwords should be stored using a suitable password-hashing algorithm, never as plaintext.
6. Nested Models for Complex API Payloads
Most production APIs don't receive flat objects containing only a handful of fields.
An order creation request might contain customer information, shipping details, and multiple line items.
You could validate everything manually, but nested Pydantic models provide a cleaner structure.
Let's build one.
from pydantic import BaseModel, Field
class Address(BaseModel):
street: str = Field(min_length=3, max_length=200)
city: str = Field(min_length=2, max_length=100)
postal_code: str = Field(min_length=3, max_length=20)
country: str = Field(min_length=2, max_length=100)
class OrderItem(BaseModel):
product_id: int = Field(gt=0)
quantity: int = Field(ge=1, le=1000)
class OrderCreate(BaseModel):
customer_id: int = Field(gt=0)
shipping_address: Address
items: list[OrderItem] = Field(min_length=1, max_length=100)Now the API can accept a payload like this:
{
"customer_id": 101,
"shipping_address": {
"street": "42 Market Road",
"city": "Jaipur",
"postal_code": "302001",
"country": "India"
},
"items": [
{
"product_id": 501,
"quantity": 2
},
{
"product_id": 502,
"quantity": 1
}
]
}Pydantic validates the nested address and each order item.
If one item has an invalid quantity, the model fails validation with an error that identifies the location of the invalid field.
This is especially useful when designing APIs for e-commerce platforms, booking systems, inventory applications, or other systems with nested request structures.
Validation is not the same as business verification
The model can confirm that product_id is a positive integer.
It cannot establish that the product exists in your database or that the current user is allowed to purchase it.
Those checks belong in your application or service layer.
For example, an order service should verify that:
The customer exists.
The customer is allowed to place the order.
Each product exists and is available.
The requested quantity can be fulfilled.
The price is calculated using trusted server-side data.
Never trust a client-provided total price simply because it passed Pydantic validation.
The client can submit a number that has the correct type and still be trying to manipulate the order total.
7. Strict Validation: When Type Coercion Is a Problem
By default, Pydantic may convert compatible values into the types declared by your model.
For example, some string representations of numbers can be converted into integers or floats in non-strict validation.
This can be convenient when working with external data, but there are situations where accepting a different input type is undesirable.
Consider an API that requires a numeric quantity:
from pydantic import BaseModel
class QuantityRequest(BaseModel):
quantity: intDepending on the input and validation mode, Pydantic may accept a compatible string representation such as "10" and convert it to an integer.
If your API contract requires the client to send an actual JSON integer, strict validation is worth considering.
from pydantic import BaseModel, ConfigDict
class QuantityRequest(BaseModel):
model_config = ConfigDict(strict=True)
quantity: intWith strict validation, a string is not automatically accepted as an integer.
For example:
from pydantic import ValidationError
try:
QuantityRequest(quantity="10")
except ValidationError as error:
print(error)Strictness can also be configured for particular fields rather than the entire model.
However, strict validation should be a deliberate decision. Some data sources naturally represent values as strings, and strict validation may require additional parsing at the appropriate boundary.
The important point is to define the contract you actually want. Don't accept every convertible value automatically, but don't reject useful input formats without a reason either.
8. Reusable Validation with Annotated and Field
As an application grows, the same validation rules may appear in multiple models.
For example, several endpoints might accept a positive product ID.
Repeating the same constraints everywhere creates duplication and makes future changes harder.
Python's Annotated type allows you to associate validation metadata with a type.
from typing import Annotated
from pydantic import Field
ProductId = Annotated[int, Field(gt=0)]Now you can reuse the type:
from pydantic import BaseModel
class ProductLookup(BaseModel):
product_id: ProductId
class CartItem(BaseModel):
product_id: ProductId
quantity: int = Field(ge=1)Both models apply the same positive-ID constraint.
This becomes especially useful for common domain concepts such as:
Positive identifiers.
Bounded page sizes.
Non-empty labels.
Valid percentages.
Bounded quantities.
You can also define reusable types for strings or other values.
Avoid creating abstractions for every field, though. A reusable type is helpful when it represents a meaningful, repeated rule. For a one-off constraint, a normal Field() declaration may be clearer.
9. Settings Management with Pydantic Settings
Validation isn't limited to API requests.
Your application also depends on configuration values, including:
Database connection URLs.
API keys.
Redis addresses.
Debug settings.
JWT configuration.
External service endpoints.
Application environment names.
A common approach is to read environment variables directly:
import os
DATABASE_URL = os.getenv("DATABASE_URL")
DEBUG = os.getenv("DEBUG", "false")The problem is that environment variables are strings, and the application needs to decide how to interpret them.
For example, this code is dangerous:
DEBUG = bool(os.getenv("DEBUG", False))If the environment variable is set to "false", the string is non-empty, so bool("false") evaluates to True.
That can lead to unexpected behavior.
Pydantic Settings solves this by allowing you to define a typed settings model.
Install it separately:
pip install pydantic-settingsCreate a configuration file.
app/config.py
from pydantic import SecretStr, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
app_name: str = "Product API"
environment: str = "development"
debug: bool = False
database_url: str
redis_url: str = "redis://localhost:6379"
jwt_secret: SecretStr
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
settings = Settings()Now create a .env file in the project root:
APP_NAME=Product API
ENVIRONMENT=development
DEBUG=false
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/products
REDIS_URL=redis://localhost:6379
JWT_SECRET=replace-with-a-development-secretPydantic Settings reads the configuration, validates its types, and makes the values available through the settings object.
For example:
from app.config import settings
print(settings.app_name)
print(settings.debug)
print(settings.database_url)The debug value is parsed as a boolean rather than being treated as an arbitrary string.
The database URL and JWT secret are required because they don't have defaults. If the required configuration is missing or invalid, application startup fails instead of allowing the application to run with incomplete settings.
This is usually desirable for production services.
Why use SecretStr?
The SecretStr type helps avoid accidentally exposing secret values when a model is printed or represented.
For example:
print(settings.jwt_secret)Pydantic masks the value in its normal representation.
When a trusted component needs the actual secret, it can access it explicitly:
secret_value = settings.jwt_secret.get_secret_value()This is a useful safety feature, but it is not a complete secret-management system.
The secret can still be exposed if your code explicitly prints the raw value, includes it in an error message, or sends it to an untrusted system.
Keep secrets out of logs and source control, and use your hosting platform's secret manager for production credentials.
10. Environment-Specific Configuration
A local development environment usually needs different settings from production.
For example, a developer might use a local PostgreSQL database and enable additional debugging. Production might use a managed database, stricter security settings, and different external service URLs.
Pydantic Settings supports environment variables and other configuration sources, so you can keep application configuration separate from business logic.
For example:
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
environment: str = "development"
debug: bool = False
database_url: str
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)The application can then use the same settings model across environments.
In development, you might load values from .env. In production, the deployment platform can provide environment variables or inject secrets through its supported configuration mechanism.
Environment variables normally take precedence over values loaded from the .env file.
This allows you to keep safe development defaults while overriding sensitive or environment-specific values during deployment.
Don't commit your .env file
Add it to .gitignore:
.env
.venv/
__pycache__/
.pytest_cache/You can commit a .env.example file containing placeholder values to document the required configuration.
For example:
APP_NAME=Product API
ENVIRONMENT=development
DEBUG=false
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/products
REDIS_URL=redis://localhost:6379
JWT_SECRET=replace-with-a-long-random-secretThese are example values only. Never place real production credentials in a committed template.
11. Validating Settings at Application Startup
Configuration errors can be difficult to debug if the application starts successfully and fails only when a particular endpoint is called.
For example, a missing API key might remain unnoticed until a user triggers an operation that calls an external service.
Typed settings help catch these problems early.
Consider:
from pydantic import Field
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
port: int = Field(default=8000, ge=1, le=65535)
max_connections: int = Field(default=20, ge=1)
request_timeout: float = Field(default=5.0, gt=0)The port must be in the valid range, the maximum connection count must be positive, and the request timeout must be greater than zero.
If a configuration value violates these rules, Pydantic raises a validation error while creating the settings object.
This prevents the application from silently using an invalid value.
However, type validation alone does not establish that a configuration is operationally correct. A database URL may be syntactically valid while pointing to an unreachable database.
For critical dependencies, you may also need startup checks, connection verification, or health checks designed for your deployment environment.
Be careful not to make an application's liveness check depend on every external service. Liveness and readiness checks have different purposes and should be designed accordingly.
12. Organizing Settings in a FastAPI Application
Let's connect the settings model to FastAPI.
A simplified project structure might look like this:
app/
├── main.py
├── config.py
├── schemas/
│ ├── user.py
│ └── product.py
├── routes/
│ ├── users.py
│ └── products.py
├── services/
│ └── product_service.py
└── database.pyIn main.py:
from fastapi import FastAPI
from app.config import settings
app = FastAPI(
title=settings.app_name,
debug=settings.debug,
)
@app.get("/health")
async def health_check():
return {
"status": "ok",
"environment": settings.environment,
}The application reads its configuration from the settings model rather than repeatedly calling os.getenv() throughout the codebase.
This provides a single place to define configuration defaults, types, and validation rules.
It also makes testing and configuration review easier.
One consideration is how settings are instantiated. A module-level settings object is convenient for many applications, but environment changes made after the object is created won't automatically update that existing object.
For most production deployments, configuration should be loaded at startup and remain stable for the process lifetime.
If tests need different settings, inject the configuration or use controlled dependency overrides instead of mutating global state unpredictably.
13. Serialization with Pydantic v2
After validating data, applications often need to convert it into dictionaries or JSON.
Pydantic v2 provides methods such as:
model_dump()model_dump_json()model_validate()model_validate_json()
For example:
from pydantic import BaseModel
class UserResponse(BaseModel):
id: int
name: str
email: str
user = UserResponse(
id=101,
name="Alex",
email="alex@example.com",
)
print(user.model_dump())The result is a Python dictionary:
{
"id": 101,
"name": "Alex",
"email": "alex@example.com",
}For JSON serialization:
json_data = user.model_dump_json()These methods are particularly useful when integrating Pydantic models with APIs, message queues, background jobs, and other systems that exchange structured data.
Excluding fields from serialized output
Sometimes an internal model contains fields that shouldn't appear in a particular response.
Pydantic allows you to control serialization:
public_data = user.model_dump(
exclude={"email"}
)This creates a dictionary without the email field.
For API responses, it's often better to define a dedicated public response model rather than rely on scattered exclusion rules. Explicit response schemas make the API contract easier to review and reduce the risk of exposing sensitive information accidentally.
14. Using Pydantic Models for External API Responses
Pydantic is also useful when consuming data from third-party services.
Imagine that your application requests product information from an external inventory service.
You receive JSON, but the external service might change its response structure or return unexpected values.
Instead of accessing dictionary keys throughout your application, define a model for the expected response.
from pydantic import BaseModel, Field
class InventoryResponse(BaseModel):
product_id: int = Field(gt=0)
available_quantity: int = Field(ge=0)
warehouse: str
external_data = {
"product_id": 501,
"available_quantity": 25,
"warehouse": "Jaipur",
}
inventory = InventoryResponse.model_validate(
external_data
)
print(inventory.available_quantity)If the external response contains invalid values, validation fails at the boundary where the data enters your application.
This is helpful because it makes integration errors easier to identify.
However, validation does not guarantee that the external service is trustworthy or that the information is accurate. It only checks that the data satisfies the rules you've defined.
You should also handle network failures, timeouts, unexpected HTTP statuses, and changes to the external service's contract.
15. Testing Pydantic Validation
Validation rules should be tested just like business logic.
A model may look correct, but edge cases can reveal mistakes in custom validators or field constraints.
Let's write a few tests for the username model.
Install pytest:
pip install pytestCreate a test file:
import pytest
from pydantic import ValidationError
from app.schemas import UserCreate
def test_valid_user():
user = UserCreate(
username="manjeet_123",
email="manjeet@example.com",
)
assert user.username == "manjeet_123"
def test_username_is_normalized():
user = UserCreate(
username=" manjeet_123 ",
email="manjeet@example.com",
)
assert user.username == "manjeet_123"
def test_username_with_spaces_is_rejected():
with pytest.raises(ValidationError):
UserCreate(
username="manjeet kumar",
email="manjeet@example.com",
)These tests assume the UserCreate model from the earlier example is available in app.schemas.
Run the tests:
pytestFor more complex models, consider testing:
Missing required fields.
Invalid field types.
Boundary values.
Nested validation errors.
Strict versus non-strict behavior.
Custom validator transformations.
Settings with missing environment variables.
Serialization of optional fields.
Invalid configuration values.
For settings tests, isolate environment variables and temporary .env files so that the result doesn't depend on a developer's machine.
A test that passes locally but fails in a clean CI environment often indicates that the application depends on undeclared environment configuration.
16. Common Mistakes When Using Pydantic
Pydantic makes validation easier, but there are still a few mistakes worth avoiding.
Putting every business rule inside validators
Validators are useful for checking and normalizing values, but they shouldn't become the place where all application logic lives.
Checking whether an email has a valid format is a validation concern.
Checking whether that email is already registered requires database access and usually belongs in a service layer.
Keeping these responsibilities separate makes models easier to reuse and test.
Assuming valid data is trustworthy
A valid request can still be malicious or unauthorized.
A positive user_id doesn't prove that the current user owns the account.
A valid product ID doesn't prove that the product exists.
A valid price doesn't prove that the price is correct.
Validation must be combined with authorization, business rules, and trusted data sources.
Using float for every number
Floating-point values are useful for many calculations, but they aren't always suitable for currency or exact decimal quantities.
Choose numeric types according to the domain and ensure that the database and serialization layers follow the same rules.
Storing secrets in source code
Pydantic Settings makes configuration easier to manage, but it doesn't automatically make secrets secure.
Use environment variables or an appropriate secret manager, restrict access to credentials, and avoid logging sensitive values.
Ignoring validation errors
Don't catch a validation error and silently replace invalid data with arbitrary defaults unless that behavior is intentional.
For important fields, rejecting invalid input is usually safer than silently changing the meaning of the request.
Creating too many tiny models
Separate request and response models are valuable when their responsibilities differ, but creating dozens of nearly identical models without a clear reason can make the application harder to navigate.
Model boundaries should reflect the API contract and the domain, not just the desire to split every field into a new class.
17. When Should You Use Pydantic?
Pydantic is particularly useful when your application works with structured data that must follow known rules.
Common examples include:
FastAPI request and response models.
Configuration and environment variable validation.
External API responses.
Nested JSON payloads.
Data processing pipelines.
Background job messages.
Application settings.
Serialization between application components.
It is less useful to introduce a Pydantic model for every small temporary dictionary that has no meaningful structure or validation requirements.
The objective is to make data boundaries explicit where that clarity improves reliability.
For a small script, basic type hints may be enough. For an API receiving requests from multiple clients, Pydantic can provide a consistent way to define and enforce data contracts.
Conclusion
Pydantic is much more than a tool for checking whether a field contains a string or an integer.
With Pydantic v2, we can define reusable validation rules, validate relationships between fields, handle nested payloads, control serialization, and make configuration management more predictable through Pydantic Settings.
These capabilities become especially valuable as an application grows. Instead of spreading validation checks across route handlers and service functions, we can define clear rules at the points where data enters the system.
But it's important to understand the limits of validation.
A model can verify that a quantity is positive, but it cannot guarantee that inventory exists. It can validate an email format, but it cannot prove ownership. It can validate a database URL's type, but it cannot guarantee that the database is available.
Those responsibilities still belong to the application architecture.
My recommendation is to start by defining clear request models, move repeated rules into reusable types, use custom validators only when necessary, and manage application configuration through a dedicated settings model.
Keep the rules close to the data they describe, test edge cases, and keep business logic separate from basic input validation.
That gives you a codebase where invalid data is easier to catch, configuration errors are easier to diagnose, and the application becomes easier to maintain as new features are added.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


