Pydantic Data Validation and Modeling
This challenge will test your ability to define and use Pydantic models for data validation and structured data representation in Python. Pydantic is incredibly useful for ensuring data integrity, providing clear data schemas, and simplifying data parsing and serialization.
Problem Description
Your task is to create Pydantic models to represent different types of user data and then validate incoming data against these models. You will need to handle various data types, including strings, integers, booleans, optional fields, and lists.
What needs to be achieved:
- Define Pydantic models for
UserandProduct. - Implement validation logic to ensure data adheres to the defined schemas.
- Demonstrate how to create instances of these models with valid and invalid data.
Key requirements:
UserModel:id: An integer, required.username: A string, required. Must be at least 3 characters long.email: A string, required. Must be a valid email format.is_active: A boolean, defaults toTrue.bio: An optional string, can beNone.
ProductModel:product_id: A string, required. Must start with "PROD-".name: A string, required.price: A float, required. Must be non-negative.tags: A list of strings, can be an empty list.
- Validation: Pydantic's built-in validators should be used where possible. For custom validation (like username length and product ID prefix), you will need to implement it.
Expected behavior:
- When valid data is provided, Pydantic models should be successfully created.
- When invalid data is provided, Pydantic should raise a
ValidationError.
Edge cases to consider:
- Missing required fields.
- Incorrect data types.
- Values failing custom validation rules (e.g., username too short, price negative).
- Optional fields being
None.
Examples
Example 1: Valid User Data
Input:
user_data = {
"id": 101,
"username": "johndoe",
"email": "john.doe@example.com",
"bio": "Passionate coder and reader."
}
Expected Output (Model Instance):
User(id=101, username='johndoe', email='john.doe@example.com', is_active=True, bio='Passionate coder and reader.')
Explanation: All fields are provided with correct types and meet the custom validation rules. is_active defaults to True.
Example 2: Invalid User Data (Username too short)
Input:
user_data = {
"id": 102,
"username": "jo",
"email": "jane.doe@example.com"
}
Expected Output (Exception):
ValidationError (details about username validation failure)
Explanation: The username "jo" is less than the required 3 characters. Pydantic will raise a ValidationError.
Example 3: Valid Product Data
Input:
product_data = {
"product_id": "PROD-ABC-123",
"name": "Wireless Mouse",
"price": 25.99,
"tags": ["electronics", "computer", "accessory"]
}
Expected Output (Model Instance):
Product(product_id='PROD-ABC-123', name='Wireless Mouse', price=25.99, tags=['electronics', 'computer', 'accessory'])
Explanation: All fields are provided with correct types and meet the custom validation rules.
Example 4: Invalid Product Data (Price negative)
Input:
product_data = {
"product_id": "PROD-XYZ-789",
"name": "Mechanical Keyboard",
"price": -50.00,
"tags": []
}
Expected Output (Exception):
ValidationError (details about price validation failure)
Explanation: The price is negative, which is not allowed. Pydantic will raise a ValidationError.
Constraints
User.usernamemust be a string and have a minimum length of 3 characters.User.emailmust be a valid email format. Pydantic has built-in support for this.User.idmust be an integer.User.is_activemust be a boolean.User.biocan be a string orNone.Product.product_idmust be a string and start with the prefix "PROD-".Product.namemust be a string.Product.pricemust be a float and be greater than or equal to 0.Product.tagsmust be a list of strings.- All required fields must be present in the input data for successful model creation.
- You should use Pydantic v1 or v2.
Notes
- Remember to import
BaseModelandvalidator(orfield_validatorin Pydantic v2) frompydantic. - For email validation, Pydantic's
EmailStrtype can be very helpful. - For custom validation logic, you can define methods within your Pydantic models.
- Consider how Pydantic handles missing fields and type coercion.