Module 5 Exercises: Pydantic Proficiency

Module 5 Exercises: Pydantic Proficiency

Hone your skills in data validation, custom logic, and secure response shaping with Pydantic and FastAPI.

Module 5 Exercises: Pydantic Proficiency

Mastering Pydantic is the difference between a "Script" and a "System." These exercises will challenge your ability to handle complex validation rules.


Exercise 1: The Account Number Constraint

Design a Pydantic model called WireTransfer. It must have:

  • sender_id (Integer)
  • receiver_id (Integer)
  • amount (Float, must be greater than zero)
  • currency (String, must be exactly 3 uppercase characters, e.g., "USD")

Exercise 2: Implementing the Date Validator

Building on Exercise 1, add a Model Validator to ensure that sender_id and receiver_id are not the same. You shouldn't be able to wire money to yourself!


Exercise 3: The Secure Output

You are building a Patient Portal for a hospital. You have a database object for a patient that looks like this:

patient_record = {
    "id": 1,
    "name": "Jane Doe",
    "ssn": "123-44-5678", # SOCIAL SECURITY NUMBER (CRITICAL SECRET)
    "blood_type": "O+",
    "insurance_id": "INS-99"
}

Design a PatientOut model and a FastAPI function signature that ensures the ssn is never sent to the client.


Self-Correction / Discussion

Exercise 1 Answer:

from pydantic import BaseModel, Field

class WireTransfer(BaseModel):
    sender_id: int
    receiver_id: int
    amount: float = Field(..., gt=0)
    currency: str = Field(..., min_length=3, max_length=3, pattern="^[A-Z]{3}$")

Exercise 2 Answer:

from pydantic import model_validator

class WireTransfer(BaseModel):
    # ... previous fields ...
    @model_validator(mode='after')
    def check_different_parties(self) -> 'WireTransfer':
        if self.sender_id == self.receiver_id:
            raise ValueError('Sender and Receiver must be different')
        return self

Exercise 3 Answer:

class PatientOut(BaseModel):
    id: int
    name: str
    blood_type: str
    insurance_id: str

@app.get("/patients/{id}", response_model=PatientOut)
async def get_patient(id: int):
    return patient_record # Pydantic will drop the 'ssn' automatically!

Summary of Module 5

You now have a "Golden Layer" between your data and the world.

  • Models: You can define strict schemas.
  • Validation: You can write deep logic to prevent bad data.
  • Shaping: You can protect secrets with output filters.

In Module 6: Dependency Injection, we will learn about FastAPI's most powerful architectural feature—the system that manages your database connections and security checks.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn