đź§Ş Validating Lists and Complex Types with parse_obj_as(...) in Pydantic

Sometimes you just need to validate a list of values or convert some raw data into proper Python types — without creating a full-blown Pydantic model for it.
That’s where parse_obj_as(...)
comes in handy.
âś… What is parse_obj_as(...)
?
It’s a helper function from Pydantic that lets you validate and parse arbitrary types — like lists, datetime
, or even nested models — using the same rules you’d get from BaseModel
.
No need to define an extra model just to wrap a list.
🔍 Example: List of datetime
strings
pythonCopyEditfrom pydantic import parse_obj_as
from typing import List
from datetime import datetime
raw_dates = ["2024-01-01T12:00:00", "2024-01-02T08:30:00"]
parsed_dates = parse_obj_as(List[datetime], raw_dates)
print(parsed_dates[0].year) # 👉 2024
Pydantic automatically converts each ISO-formatted string into a datetime
object. Super clean.
đź§± Example: List of Pydantic models
Let’s say you receive this data from an API:
pythonCopyEditdata = [
{"id": 1, "name": "banana"},
{"id": 2, "name": "apple"},
]
You can validate it like this:
pythonCopyEditfrom pydantic import BaseModel, parse_obj_as
from typing import List
class Item(BaseModel):
id: int
name: str
items = parse_obj_as(List[Item], data)
print(items[0].name) # 👉 banana
It gives you proper objects with full validation and autocomplete support in your editor.
⚠️ What if the data is invalid?
You’ll get a nice ValidationError
, as expected:
pythonCopyEditbad_data = [{"id": "abc", "name": "banana"}]
parse_obj_as(List[Item], bad_data)
# ValidationError: id is not a valid integer
đź§ TL;DR
Use parse_obj_as(...)
when:
You want to validate or convert raw data into Python types
You’re dealing with lists or generics (like
List[int]
,List[Model]
)You don’t want to define a wrapper
BaseModel
just for the structure
It’s one of those small Pydantic features that saves a lot of boilerplate.
Subscribe to my newsletter
Read articles from Pedro Buzzi Filho directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
