Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 5 · Lab · 25 min · revision 2

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

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.

Create an environment and install Pydantic
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.

tickets_raw.csv
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.

Step 1
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}")
Expected output
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.

Step 2a: the Ticket model
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 value

What 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=True trims string fields before the length and pattern checks, so a body of three spaces counts as empty.
  • ticket_id: int accepts 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_id must be exactly six digits, which protects the leading zeros a spreadsheet tends to strip.
  • Literal[...] lists the only allowed values. AwareDatetime parses the timestamp and requires it to carry a time zone, so an ambiguous local time cannot slip in.
  • priority is optional and, when present, between 1 and 4.
  • The two field_validator methods use mode="before", so they run on the raw input before the type check. One normalises the language code; the other turns the empty CSV field into None, which the optional field accepts.
Step 2b: validate one row
ticket = Ticket.model_validate(raw_rows[1])
print(ticket.model_dump_json(indent=2))
print(type(ticket.ticket_id).__name__, ticket.created_at.tzname())
Expected output
{
  "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.

Step 3
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"])
Expected output
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 4

exc.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 as less_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.

Step 4
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)}")
Expected output
read 10, valid 5, rejected 5

A 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 with encoding="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; the or "(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

Step 5
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))
Expected output
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_mismatch on account_id (4217): someone opened the export in a spreadsheet and the leading zeros were lost.
  • datetime_from_date_parsing (month 13) and timezone_aware (2024-05-05, no time or zone): two different date problems in the source system.
  • literal_error on language and source: 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

Practice check · 3 questions

Pydantic validation behaviour

Use the `Ticket` model from this lab as the starting point for each question.

Q1. A new export adds an `agent_notes` column to every row. With `ConfigDict(extra='forbid')`, what happens when you validate a row?
Q2. The CSV gives `ticket_id` as the string `'1042'`, and the field is declared `ticket_id: int` without strict mode. What does `model_validate` produce for that field?
Q3. The lab model already sets `str_strip_whitespace=True`. Why does it still need the `normalise_language` validator with `mode='before'` for `language` values such as `' EN '` and `'Vi'`?
Practice only: not graded, not saved, not evidence.

09. Apply it (stretch)

Extend the lab towards the skill's practice project:

  1. Add a second validator on created_at (the default after mode is fine) that returns value.astimezone(timezone.utc), so ticket 1046 is stored as 2024-05-04T02:30:00Z. Add from datetime import timezone to the imports of step 2a.
  2. 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 add import pandas as pd. Then: pd.DataFrame([t.model_dump() for t in valid]).to_parquet("tickets_valid.parquet", index=False). Read back only ticket_id and created_at and check that their dtypes are an integer and a UTC timestamp.
  3. Export the quarantine as a CSV for the support team, one row per reject with line, ticket_id and the reasons joined by ; .
  4. 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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check