Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 1, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 1, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 1, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 1, 2025

      7 MagSafe accessories that I recommend every iPhone user should have

      June 1, 2025

      I replaced my Kindle with an iPad Mini as my ebook reader – 8 reasons why I don’t regret it

      June 1, 2025

      Windows 11 version 25H2: Everything you need to know about Microsoft’s next OS release

      May 31, 2025

      Elden Ring Nightreign already has a duos Seamless Co-op mod from the creator of the beloved original, and it’ll be “expanded on in the future”

      May 31, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Student Record Android App using SQLite

      June 1, 2025
      Recent

      Student Record Android App using SQLite

      June 1, 2025

      When Array uses less memory than Uint8Array (in V8)

      June 1, 2025

      Laravel 12 Starter Kits: Definite Guide Which to Choose

      June 1, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Photobooth is photobooth software for the Raspberry Pi and PC

      June 1, 2025
      Recent

      Photobooth is photobooth software for the Raspberry Pi and PC

      June 1, 2025

      Le notizie minori del mondo GNU/Linux e dintorni della settimana nr 22/2025

      June 1, 2025

      Rilasciata PorteuX 2.1: Novità e Approfondimenti sulla Distribuzione GNU/Linux Portatile Basata su Slackware

      June 1, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»A Step-by-Step Tutorial on Robustly Validating and Structuring User, Product, and Order Data with Pydantic in Python

    A Step-by-Step Tutorial on Robustly Validating and Structuring User, Product, and Order Data with Pydantic in Python

    February 12, 2025

    In many modern Python applications, especially those that handle incoming data (e.g., JSON payloads from an API), ensuring that the data is valid, complete, and properly typed is crucial. Pydantic is a powerful library that allows you to define models for your data using standard Python-type hints and then automatically validate any incoming data against these models. In this example, we’ll showcase how to model a typical use case: a user placing an order for products. We’ll use Pydantic to define User, Product, and Order models, ensuring that data like emails, prices, quantities, and user details adhere to our specified constraints.

    Step 1: Install Dependencies

    Copy CodeCopiedUse a different Browser
    pip install pydantic
    pip install pydantic[email]
    

    Use pip install pydantic to install the core library, enabling data validation with Python-type hints. Also, run pip install pydantic[email] for built-in email validation features.

    Step 2: Define the Pydantic Models (User, Product, and Order)

    Copy CodeCopiedUse a different Browser
    from typing import List, Optional
    from pydantic import BaseModel, Field, EmailStr, conint, ValidationError
    
    
    # Define the models
    class User(BaseModel):
        name: str = Field(..., min_length=1, max_length=50, description="User's full name")
        email: EmailStr = Field(..., description="User's email address, validated by Pydantic")
        age: Optional[conint(ge=0, le=120)] = Field(None, description="Optional age with a realistic range")
        phone_number: Optional[str] = Field(None, pattern=r'^+?[1-9]d{1,14}$', description="Optional phone number, E.164 format")
    
    
    class Product(BaseModel):
        name: str = Field(..., min_length=1, max_length=100)
        price: float = Field(..., gt=0, description="Price must be greater than zero")
        quantity: conint(gt=0) = Field(..., description="Quantity must be greater than zero")
    
    
    class Order(BaseModel):
        order_id: int = Field(..., gt=0, description="Order ID must be a positive integer")
        user: User
        products: List[Product] = Field(..., description="A list of products in the order")
    
    
        # Computed property
        @property
        def total_cost(self) -> float:
            return sum(product.price * product.quantity for product in self.products)

    Through the above code, these three Pydantic models, User, Product, and Order, provide a structured, validated approach to managing application data. The user enforces constraints for name, email, optional age, and an optional phone number matching a pattern. The product ensures a valid name length, a positive price, and a non-zero quantity. Finally, the Order ties the user and products together while computing the total cost of the order.

    Step 3: Implement Validation in the main() Function

    Copy CodeCopiedUse a different Browser
    def main():
        # Example of a valid user dictionary
        user_data = {
            "name": "Jane Doe",
            "email": "jane.doe@example.com",
            "age": 30,
            "phone_number": "+1234567890"
        }
    
    
        # Example of product data
        products_data = [
            {"name": "Keyboard", "price": 49.99, "quantity": 1},
            {"name": "Mouse", "price": 19.99, "quantity": 2}
        ]
    
    
        # Combine user and products in an order
        order_data = {
            "order_id": 101,
            "user": user_data,
            "products": products_data
        }
    
    
        try:
            # Instantiate models to trigger validation
            valid_user = User(**user_data)
            print("User Model:", valid_user)
    
    
            valid_products = [Product(**pd) for pd in products_data]
            print("Product Models:", valid_products)
    
    
            valid_order = Order(**order_data)
            print("Order Model:", valid_order)
            print(f"Total cost of the order: {valid_order.total_cost}")
    
    
        except ValidationError as e:
            print("Validation Error:", e)

    Now, this main() function simulates receiving data for a user and multiple products, then creates and validates the corresponding User, Product, and Order instances. It demonstrates how Pydantic raises a ValidationError if any data fails validation and prints out validated models and the computed total cost otherwise.

    Step 4: Execute the Program

    Copy CodeCopiedUse a different Browser
    # Run the main() function
    main()
    

    We call main() to execute the demonstration, which validates our example user, product, and order data. After running the function, it prints out the validated models and any errors if the data fails validation.

    Output

    Copy CodeCopiedUse a different Browser
    User Model: name='Jane Doe' email='jane.doe@example.com' age=30 phone_number='+1234567890' Product Models: [Product(name='Keyboard', price=49.99, quantity=1), Product(name='Mouse', price=19.99, quantity=2)] Order Model: order_id=101 user=User(name='Jane Doe', email='jane.doe@example.com', age=30, phone_number='+1234567890') products=[Product(name='Keyboard', price=49.99, quantity=1), Product(name='Mouse', price=19.99, quantity=2)] Total cost of the order: 89.97

    The output for the code will be as above.

    In this example, we demonstrated how Pydantic can define and validate data models for a User, Product, and Order within a real-world workflow. Pydantic ensures that any data fed into these models is correct by specifying field types, constraints, and custom validations. This helps you catch errors early, simplify your code logic, and boost reliability in data-intensive applications.


    Here is the Colab Notebook for the above project. Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 75k+ ML SubReddit.

    🚨 Recommended Open-Source AI Platform: ‘IntellAgent is a An Open-Source Multi-Agent Framework to Evaluate Complex Conversational AI System’ (Promoted)

    The post A Step-by-Step Tutorial on Robustly Validating and Structuring User, Product, and Order Data with Pydantic in Python appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleOpenAI Introduces Competitive Programming with Large Reasoning Models
    Next Article Frame-Dependent Agency: Implications for Reinforcement Learning and Intelligence

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    June 1, 2025
    Machine Learning

    BOND 2025 AI Trends Report Shows AI Ecosystem Growing Faster than Ever with Explosive User and Developer Adoption

    June 1, 2025
    Leave A Reply Cancel Reply

    Hostinger

    Continue Reading

    Mirantis Launches Open Source Project for Platform Engineering that Accelerates Innovation for Modern Distributed Workloads

    Tech & Work

    Understanding Laravel’s Context Capabilities : Testing with Context

    Development

    Motion Highlights #3

    News & Updates

    AlmaLinux 9.6: La Nuova Versione Libera e Compatibile con Red Hat Enterprise Linux 9.6

    Linux
    GetResponse

    Highlights

    30+ Notion Templates for Creative Designers

    July 26, 2024

    Post Content Source: Read More 

    AI model performance: Is it reasoning or simply reciting?

    July 14, 2024

    Some of the announcements coming to Laracon US

    August 19, 2024

    Prestazioni a Confronto: Quale Scegliere tra il kernel Linux Liquorix e il kernel Linux 6.12?

    December 23, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.