Schema Validation with Pydantic Models
Validate every row of a messy ticket export with a Pydantic v2 model, keep the valid rows and quarantine the rest with a machine-readable reason.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Read the rows as text
- Step 2: Describe a valid ticket
- Step 3: Read a validation error
- Step 4: Validate every row and quarantine failures
- Step 5: Inspect the quarantine
- Troubleshooting
- Check your understanding
- Apply it (stretch)
- Review prompt
Lessons of Data Handling
- JSON, CSV, Parquet and Text Encodings Concept · 15 min
- Round-Tripping Records Safely, CSV Versus Parquet Worked example · 20 min
- Schema Validation with Pydantic Models Lab · 25 min
- Tabular Cleaning with pandas Lab · 25 min
- Check: Clean a Messy Dataset Knowledge check · 6 questions
What you will learn
- Validate records against a schema and report or quarantine invalid rows with a reason.
Prerequisites: Python Foundations
01. Goal and setup
A helpdesk export is about to feed your RAG corpus. Some rows are fine, some are broken, and you cannot fix the source today. Dropping the broken rows silently hides the problem; crashing on the first one blocks the good data. The pattern you will build sits in between: validate every row against a declared schema, pass the valid ones on, and quarantine the rest together with the reason they failed.
By the end you will have two files:
tickets_valid.jsonl: typed, normalised tickets, one JSON object per line;tickets_rejects.jsonl: one entry per failed row, with its line number, every reason it failed and the raw row exactly as read.
You need Python 3.12 or later (check with python3 --version) and Pydantic v2. The lab was tested with Python 3.12 and Pydantic 2.14.3, the version pinned below; any later 2.x release should give the same type codes and counts. Run the steps in order in one session, either a Jupyter notebook with one cell per step or a single script you extend, because each step uses names from the previous ones.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "pydantic==2.14.3"Save the sample below as tickets_raw.csv, encoded as UTF-8. Several rows are broken on purpose; try to spot the problems before the validator does. Ticket 1044 has a body of three spaces, and ticket 1050 has a two-line body inside quotes.
ticket_id,account_id,language,created_at,source,priority,text
1042,004217,vi,2024-05-02T09:15:00Z,email,2,"Không đăng nhập được, lỗi ""E42"""
1043,000981,FR ,2024-05-03T14:40:00Z,chat,,Facture en double
1044,120554,en,2024-05-03T16:05:00Z,web,1," "
1045,4217,en,2024-05-04T08:00:00Z,email,3,Password reset link expired
1046,120554,en,2024-05-04T09:30:00+07:00,chat,2,Export to CSV drops accents
1047,000981,de,2024-13-05T10:00:00Z,email,2,Rechnung fehlt
1048,004217,es,2024-05-05T11:20:00Z,phone,9,No puedo cambiar el plan
1049,120554,en,2024-05-05,web,2,API returns 500 on /search
1050,004217,vi,2024-05-06T07:45:00Z,chat,1,"Lỗi khi xuất hóa đơn
Không tải được PDF"
1051,000981,en,2024-05-06T10:10:00Z,web,4,How do I rotate my API key?02. Step 1: Read the rows as text
Read the file with the csv module. encoding='utf-8-sig' copes with a byte order mark if a spreadsheet added one, and newline='' keeps the two-line body of ticket 1050 in one field. Every value arrives as a string; turning strings into typed values is the model's job, not the reader's.
import csv
with open("tickets_raw.csv", encoding="utf-8-sig", newline="") as f:
raw_rows = list(csv.DictReader(f))
print(len(raw_rows), "rows")
for key, value in raw_rows[1].items():
print(f"{key:>10}: {value!r}")10 rows
ticket_id: '1043'
account_id: '000981'
language: 'FR '
created_at: '2024-05-03T14:40:00Z'
source: 'chat'
priority: ''
text: 'Facture en double'Eleven physical lines of data, ten records: the quoted line break in ticket 1050 was read correctly. Ticket 1043 already shows two kinds of mess: a language code with a capital letter and a trailing space, and an empty priority.
03. Step 2: Describe a valid ticket
A Pydantic model is a class whose type annotations are the schema. Each rule sits next to the field it constrains, so a reviewer can read the whole contract in one place.
from typing import Literal
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator
class Ticket(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
ticket_id: int = Field(gt=0)
account_id: str = Field(pattern=r"^\d{6}$")
language: Literal["en", "vi", "fr", "de"]
created_at: AwareDatetime
source: Literal["email", "chat", "web"]
priority: int | None = Field(default=None, ge=1, le=4)
text: str = Field(min_length=1)
@field_validator("language", mode="before")
@classmethod
def normalise_language(cls, value: object) -> object:
return value.strip().lower() if isinstance(value, str) else value
@field_validator("priority", mode="before")
@classmethod
def blank_means_missing(cls, value: object) -> object:
return None if value == "" else valueWhat each part does:
extra='forbid'makes an unexpected column an error. A CSV row always carries every header, so this catches renamed or added columns instead of silently ignoring them.str_strip_whitespace=Truetrims string fields before the length and pattern checks, so a body of three spaces counts as empty.ticket_id: intaccepts the string"1043"and converts it. By default Pydantic runs in lax mode, which converts obviously numeric strings; that is what you want for CSV input, where everything is text.account_idmust be exactly six digits, which protects the leading zeros a spreadsheet tends to strip.Literal[...]lists the only allowed values.AwareDatetimeparses the timestamp and requires it to carry a time zone, so an ambiguous local time cannot slip in.priorityis optional and, when present, between 1 and 4.- The two
field_validatormethods usemode="before", so they run on the raw input before the type check. One normalises the language code; the other turns the empty CSV field intoNone, which the optional field accepts.
ticket = Ticket.model_validate(raw_rows[1])
print(ticket.model_dump_json(indent=2))
print(type(ticket.ticket_id).__name__, ticket.created_at.tzname()){
"ticket_id": 1043,
"account_id": "000981",
"language": "fr",
"created_at": "2024-05-03T14:40:00Z",
"source": "chat",
"priority": null,
"text": "Facture en double"
}
int UTC'FR ' became fr, the empty priority became null, the id is a real int and the timestamp knows it is UTC. The model has done the conversion and the checking in one call.
04. Step 3: Read a validation error
Now validate ticket 1048, which breaks three rules. Pydantic does not stop at the first problem: it checks every field and raises one ValidationError that lists them all.
from pydantic import ValidationError
row_1048 = next(row for row in raw_rows if row["ticket_id"] == "1048")
try:
Ticket.model_validate(row_1048)
except ValidationError as exc:
print(exc.error_count(), "errors")
for error in exc.errors():
print(error["loc"], error["type"], "|", error["msg"])3 errors
('language',) literal_error | Input should be 'en', 'vi', 'fr' or 'de'
('source',) literal_error | Input should be 'email', 'chat' or 'web'
('priority',) less_than_equal | Input should be less than or equal to 4exc.errors() returns a list of dictionaries. The keys you will use most:
loc: a tuple path to the failing value, such as('priority',). For nested models it has several parts.type: a short, stable code such asless_than_equal. Use it in code, for counting and for routing.msg: a sentence for people. Its wording can change between Pydantic versions, so do not match on it.input: the value that failed.
Store both type and msg with a rejected row: one for the pipeline, one for the person who fixes the source.
05. Step 4: Validate every row and quarantine failures
Loop over the file once more. Valid rows become Ticket objects; each failure becomes a quarantine entry with the line number, the reasons and the untouched raw row. reader.line_num counts physical lines read so far, so for a multi-line record it points at the record's last line, which is what someone opening the file in an editor needs.
import json
def reasons(exc: ValidationError) -> list[dict]:
return [
{
"field": ".".join(str(part) for part in error["loc"]) or "(row)",
"type": error["type"],
"message": error["msg"],
}
for error in exc.errors()
]
valid: list[Ticket] = []
rejects: list[dict] = []
with open("tickets_raw.csv", encoding="utf-8-sig", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
try:
valid.append(Ticket.model_validate(row))
except ValidationError as exc:
rejects.append(
{"line": reader.line_num, "reasons": reasons(exc), "row": row}
)
with open("tickets_valid.jsonl", "w", encoding="utf-8") as f:
for ticket in valid:
print(ticket.model_dump_json(), file=f)
with open("tickets_rejects.jsonl", "w", encoding="utf-8") as f:
for reject in rejects:
print(json.dumps(reject, ensure_ascii=False), file=f)
total = len(valid) + len(rejects)
print(f"read {total}, valid {len(valid)}, rejected {len(rejects)}")read 10, valid 5, rejected 5A few choices worth noticing:
model_dump_json()serialises the timestamp as ISO 8601 and writes non-ASCII text as UTF-8 characters, so the file must be opened withencoding="utf-8".- The quarantine keeps the raw row, not a half-converted one, so the entry can be fixed and replayed through the same model.
- An error from a whole-model rule has an empty
loc; theor "(row)"fallback still gives it a readable field name. - The counts add up: read equals valid plus rejected. Print this line on every run, and treat a sudden jump in rejects as an alert, not as noise.
06. Step 5: Inspect the quarantine
from collections import Counter
with open("tickets_rejects.jsonl", encoding="utf-8") as f:
quarantined = [json.loads(line) for line in f]
for item in quarantined:
fields = ", ".join(reason["field"] for reason in item["reasons"])
print(f"line {item['line']:>2} ticket {item['row']['ticket_id']} {fields}")
counts = Counter(r["type"] for item in quarantined for r in item["reasons"])
for error_type, n in counts.most_common():
print(n, error_type)
print(json.dumps(quarantined[0], indent=2, ensure_ascii=False))line 4 ticket 1044 text
line 5 ticket 1045 account_id
line 7 ticket 1047 created_at
line 8 ticket 1048 language, source, priority
line 9 ticket 1049 created_at
2 literal_error
1 string_too_short
1 string_pattern_mismatch
1 datetime_from_date_parsing
1 less_than_equal
1 timezone_aware
{
"line": 4,
"reasons": [
{
"field": "text",
"type": "string_too_short",
"message": "String should have at least 1 character"
}
],
"row": {
"ticket_id": "1044",
"account_id": "120554",
"language": "en",
"created_at": "2024-05-03T16:05:00Z",
"source": "web",
"priority": "1",
"text": " "
}
}Each error type points at a different upstream cause, which is why the codes are worth counting:
string_pattern_mismatchonaccount_id(4217): someone opened the export in a spreadsheet and the leading zeros were lost.datetime_from_date_parsing(month 13) andtimezone_aware(2024-05-05, no time or zone): two different date problems in the source system.literal_erroronlanguageandsource: a new language and a new channel the schema does not know yet. That might be bad data, or it might mean the schema needs updating; the quarantine lets someone decide instead of the code guessing.
Ticket 1046 passed with a +07:00 offset. It is a valid, time-zone-aware timestamp, just not in UTC; the stretch task below normalises it.
07. Troubleshooting
08. Check your understanding
09. Apply it (stretch)
Extend the lab towards the skill's practice project:
- Add a second validator on
created_at(the default after mode is fine) that returnsvalue.astimezone(timezone.utc), so ticket 1046 is stored as2024-05-04T02:30:00Z. Addfrom datetime import timezoneto the imports of step 2a. - Write the valid tickets to Parquet as well. This needs pandas and pyarrow, which the lab has not installed: run
pip install "pandas==3.1.1" "pyarrow==26.0.1"(the versions of lesson 2) and addimport pandas as pd. Then:pd.DataFrame([t.model_dump() for t in valid]).to_parquet("tickets_valid.parquet", index=False). Read back onlyticket_idandcreated_atand check that their dtypes are an integer and a UTC timestamp. - Export the quarantine as a CSV for the support team, one row per reject with
line,ticket_idand the reasons joined by;. - Run the pipeline on a real export from your own project and look at the error-type counts before you change any rule.
10. Review prompt
Without looking back, write down the three parts of a quarantine entry from this lab and say what each is for. Then name one problem in a ticket export that a per-row schema like Ticket cannot detect, and say which tool in the next lesson would catch it.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.