Stop Writing Messy Validation Code: A Beginner-Friendly Guide to Pydantic in Python
Shubham Chou
·
2026-04-27
·
via Artificial Intelligence in Plain English - Medium
Pydantic Beginner Guide When you build Python applications, you often receive data from many places: APIs, forms, JSON files, databases, CSV files, user inputs, or environment variables. The problem is simple: You cannot always trust the data. Maybe the age comes as "25" instead of 25. Maybe an email field is missing. Maybe price is negative. Maybe an API sends extra fields you do not need. Without validation, your program may break later in confusing ways. That is where Pydantic helps. Pydantic is a Python library used for data validation, parsing, and serialization using normal Python type hints. The official documentation describes it as being powered by type hints, with validation and serialization controlled by annotations, and its core validation logic is written in Rust for speed. What Is Pydantic? pydantic Pydantic lets you define the structure of your data using Python classes. Instead of manually writing many if conditions, you describe what the data should look like, and Pydantic checks it for you. Example: from pydantic import BaseModel class User(BaseModel): name: str age: int email: str user = User(name="Shubham", age="25", email="test@example.com") print(user) print(type(user.age)) Output: name='Shubham' age=25 email='test@example.com' <class 'int'> Notice something important. We passed age as a string: age="25" But Pydantic converted it into an integer: 25 This is one of the biggest reasons Pydantic is useful. It validates and also parses data into the correct type. Why Should You Use Pydantic? You should use Pydantic when your code depends on data being correct. Without Pydantic, you may write code like this: def create_user(data): if "name" not in data: raise ValueError("name is required") if "age" not in data: raise ValueError("age is required") if not isinstance(data["age"], int): raise ValueError("age must be an integer") return data This becomes messy very quickly. With Pydantic: from pydantic import BaseModel class User(BaseModel): name: str age: int data = {"name": "Amit", "age": 30} user = User(**data) print(user) Cleaner. Safer. Easier to read. Pydantic is especially useful because it supports validation, serialization to dictionaries or JSON, and JSON schema generation for integration with tools and APIs. Where Is Pydantic Useful? Pydantic is useful in many real-world Python projects. Pydantic Usefulness 1. API Development If you are using FastAPI , Pydantic is commonly used to validate request and response data. Example: from pydantic import BaseModel class Product(BaseModel): name: str price: float in_stock: bool incoming_data = { "name": "Laptop", "price": "59999.99", "in_stock": "true" } product = Product(**incoming_data) print(product) print(type(product.price)) print(type(product.in_stock)) Output: name='Laptop' price=59999.99 in_stock=True <class 'float'> <class 'bool'> This is very useful when APIs send data in string format. 2. Validating JSON Data Suppose you receive JSON from an external API: api_response = { "id": 101, "username": "john_doe", "followers": "1200" } You can validate it like this: from pydantic import BaseModel class Profile(BaseModel): id: int username: str followers: int profile = Profile(**api_response) print(profile.followers) print(type(profile.followers)) Output: 1200 <class 'int'> Your code now works with clean data. 3. Data Pipelines and ETL In data engineering or analytics, bad data is common. Example: from pydantic import BaseModel, Field class SalesRecord(BaseModel): order_id: int customer_name: str amount: float = Field(gt=0) country: str record = SalesRecord( order_id="1001", customer_name="Rahul", amount=499.99, country="India" ) print(record) Here: amount: float = Field(gt=0) means amount must be greater than zero. If someone passes a negative amount: from pydantic import ValidationError try: bad_record = SalesRecord( order_id="1002", customer_name="Aman", amount=-50, country="India" ) except ValidationError as e: print(e) Pydantic will show a clear validation error. The Field() function lets you add constraints such as minimum value, maximum value, string length, default values, and descriptions. 4. Configuration and Settings Pydantic is also useful for managing application settings. For example, instead of hardcoding database settings everywhere, you can define a clean settings model. from pydantic import BaseModel class AppConfig(BaseModel): app_name: str debug: bool database_url: str max_connections: int config = AppConfig( app_name="My App", debug="true", database_url="postgresql://localhost:5432/mydb", max_connections="10" ) print(config) Output: app_name='My App' debug=True database_url='postgresql://localhost:5432/mydb' max_connections=10 This helps make your application more reliable. Understanding BaseModel Most beginner Pydantic code starts with BaseModel. from pydantic import BaseModel BaseModel is the base class that gives your class validation power. Example: class Student(BaseModel): name: str marks: int passed: bool This tells Pydantic: name should be a string marks should be an integer passed should be a boolean Now you can create a validated object: student = Student(name="Priya", marks="85", passed="true") print(student) Output: name='Priya' marks=85 passed=True Handling Validation Errors When invalid data is passed, Pydantic raises a ValidationError. from pydantic import BaseModel, ValidationError class Employee(BaseModel): name: str salary: float try: employee = Employee(name="Ravi", salary="not-a-number") except ValidationError as e: print(e) Output will explain what went wrong. This is better than your application failing later with confusing bugs. Using Field for Better Validation Field allows you to add rules. from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(min_length=3, max_length=20) age: int = Field(ge=18) Here: min_length=3 means username must have at least 3 characters. ge=18 means age must be greater than or equal to 18. Example: try: user = User(username="ab", age=16) except ValidationError as e: print(e) This will fail because: username is too short age is below 18 Nested Models: Validating Complex Data Pydantic is very useful when your data has nested structure. Example: from pydantic import BaseModel class Address(BaseModel): city: str country: str pincode: int class Customer(BaseModel): name: str address: Address data = { "name": "Sneha", "address": { "city": "Bangalore", "country": "India", "pincode": "560001" } } customer = Customer(**data) print(customer) print(type(customer.address.pincode)) Output: name='Sneha' address=Address(city='Bangalore', country='India', pincode=560001) <class 'int'> This is powerful for APIs, JSON files, and real-world applications. Converting Pydantic Models to Dictionary or JSON Pydantic models can be converted into dictionaries or JSON. In Pydantic v2, model_dump() is commonly used to convert a model to a dictionary, and Pydantic documentation explains serialization as converting models into Python or JSON-compatible outputs. from pydantic import BaseModel class Book(BaseModel): title: str author: str price: float book = Book(title="Python Basics", author="John Smith", price=499.99) book_dict = book.model_dump() book_json = book.model_dump_json() print(book_dict) print(book_json) Output: {'title': 'Python Basics', 'author': 'John Smith', 'price': 499.99} {"title":"Python Basics","author":"John Smith","price":499.99} This is useful when sending data back to APIs, storing data, or logging clean outputs. Custom Validation Example Sometimes basic type checking is not enough. For example, you may want to reject usernames containing spaces. from pydantic import BaseModel, field_validator, ValidationError class Account(BaseModel): username: str @field_validator("username") @classmethod def username_must_not_have_spaces(cls, value): if " " in value: raise ValueError("username must not contain spaces") return value try: account = Account(username="john doe") except ValidationError as e: print(e) This gives you full control over validation logic. Real-World Example: Validating an API Request Imagine you are building an e-commerce checkout system. from pydantic import BaseModel, Field from typing import List class Item(BaseModel): product_id: int name: str quantity: int = Field(gt=0) price: float = Field(gt=0) class Order(BaseModel): order_id: int customer_email: str items: List[Item] order_data = { "order_id": "5001", "customer_email": "customer@example.com", "items": [ { "product_id": "101", "name": "Keyboard", "quantity": 2, "price": "1499.99" }, { "product_id": 102, "name": "Mouse", "quantity": 1, "price": 799.50 } ] } order = Order(**order_data) print(order) print(order.model_dump()) Pydantic validates the full order, including the nested item list. This is exactly where Pydantic becomes valuable: APIs, checkout systems, dashboards, data pipelines, ML apps, and backend services. When Should You Not Use Pydantic? Pydantic is powerful, but you do not need it everywhere. You may not need Pydantic for: Very small scripts Simple variables inside one function Code where data is already fully controlled Performance-critical loops where millions of objects are created repeatedly But when your app receives external or unpredictable data, Pydantic is usually a smart choice. Pydantic vs Manual Validation Why Use Pydantic? Manual validation: if not isinstance(age, int): raise ValueError("Age must be integer") Pydantic validation: class User(BaseModel): age: int Manual validation becomes harder as your data grows. Pydantic keeps your code clean because the validation rules stay close to the data structure. Beginner Mental Model Think of Pydantic like a security guard for your data . Before data enters your application, Pydantic checks: Is the required field present? Is the type correct? Can it be converted safely? Does it follow rules like minimum length or positive number? Is the nested structure valid? Only clean data gets through. Final Takeaway Pydantic is one of the most useful libraries for writing reliable Python applications. It helps you: Validate incoming data Convert data into correct types Catch errors early Reduce manual if checks Work cleanly with APIs and JSON Serialize data into dictionaries or JSON Build safer backend, data, and ML applications If you are learning Python seriously, especially for APIs, data engineering, automation, or AI apps, Pydantic is worth learning early. Sources: Official Documentation Pydantic Docs — https://docs.pydantic.dev GitHub Repository (Code + Examples) Pydantic GitHub — https://github.com/pydantic/pydantic A quick note before you go 👋 I break down real AI shifts before they hit the mainstream 🚀 Click Follow now so you do not miss what matters next and drop a clap 👏 if this helped. Stop Writing Messy Validation Code: A Beginner-Friendly Guide to Pydantic in Python was originally published in Artificial Intelligence in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。