How to parse list of models with Pydantic

pydantic dataclass
pydantic django
pydantic datatypes
pydantic config
pydantic github
pydantic vs marshmallow
pydantic vs attrs
pydantic print

I use Pydantic to model the requests and responses to an API.

I defined a User class:

from pydantic import BaseModel

class User(BaseModel):
  name: str
  age: int

My API returns a list of users which I retrieve with requests and convert into a dict:

users = [{"name": "user1", "age": 15}, {"name": "user2", "age": 28}]

How can I convert this dict to a list of User instances?

My solution for now is

user_list = []
for user in users:
  user_list.append(User(**user))

This is now possible using parse_obj_as.

from pydantic import parse_obj_as

users = [
    {"name": "user1", "age": 15}, 
    {"name": "user2", "age": 28}
]

m = parse_obj_as(List[User], users)

Models, List: see Typing Iterables below for more detail on parsing and validation; typing. pydantic import BaseModel class Model(BaseModel): simple_list: list = None� For this pydantic provides the create_model method to allow models to be created on the fly. from pydantic import BaseModel, create_model DynamicFoobarModel = create_model('DynamicFoobarModel', foo=(str, ), bar=123) class StaticFoobarModel(BaseModel): foo: str bar: int = 123.

To confirm and expand the previous answer, here is an "official" answer at pydantic-github - All credits to "dmontagu":

The "right" way to do this in pydantic is to make use of "Custom Root Types". You still need to make use of a container model:

class UserList(BaseModel):
    __root__: List[User]
but then the following will work:

UserList.parse_obj([
    {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']},
    {'id': '456', 'signup_ts': '2017-06-02 12:22', 'friends': ['you']},
])

(and will put the values inside the root property).

Unfortunately, I think there is not good serialization support for this yet, so I think when you go to return the results, if you want to return just a list you'll still need to return UserList.root.

I don't think there is currently a unified interface that gets you a serialized/unstructured version of the model that respects the root_model, but if this is what you are looking for, it could be worth building.

Field Types, from datetime import datetime from typing import List from pydantic import that gets you a serialized/unstructured version of the model that respects if page is not None: serializer = MyModelList.parse_obj(page) return� You can also generate a top-level JSON Schema that only includes a list of models and related sub-models in its definitions: import json from pydantic import BaseModel from pydantic.schema import schema class Foo ( BaseModel ): a : str = None class Model ( BaseModel ): b : Foo class Bar ( BaseModel ): c : int top_level_schema = schema ([ Model

You can try this

from typing import List
from pydantic import BaseModel

class User(BaseModel):
  name: str
  age: int

class Users(BaseModel):
    users: List[User]

users = [{"name": "user1", "age": 15}, {"name": "user2", "age": 28}]
m = Users(users=users)
print(m.dict())

Body - Nested Models, I would appreciate an additional helper functions for parsing types like: List[ Model] # where model is a pydantic model; Dict[int, List[Model]]. use of recursive pydantic models, typing's standard types (e.g. List, Tuple, Dict etc.) and validators allow complex data schemas to be clearly and easily defined, validated, and parsed. extensible pydantic allows custom data types to be defined or you can extend validation with methods on a model decorated with the validator decorator.

You can use the __root__ Pydantic keyword:

from typing import List
from pydantic import BaseModel

class User(BaseModel):
  name: str
  age: int

class UserList(BaseModel):
  __root__: List[User]     # ⯇-- __root__

To build the JSON response:

user1 = {"name": "user1", "age": 15}
user2 = {"name": "user2", "age": 28}

user_list = UserList(__root__=[])
user_list.__root__.append(User(**user1))
user_list.__root__.append(User(**user2))

Your API web framework can jsonify user_list to be returned as a JSON array (within the response body).

Question: serializing a list of objects � Issue #675 � samuelcolvin , from datetime import datetime from typing import List, Optional from pydantic when a BaseModel -type model field causes a ValidationError during parsing,� Exporting models. As well as accessing model attributes directly via their names (e.g. model.foobar), models can be converted and exported in a number of ways: model.dict()🔗 This is the primary way of converting a model to a dictionary. Sub-models will be recursively converted to dictionaries. Arguments:

You could consider using a list comprehension along with dict unpacking to the User constructor

user_list = [
  User(**user) for user in users
]

parse_generic method to allow parsing non Model types � Issue , Now we can change the field names to camelCase but that does not follow the PEP-8 standard. Pydantic Aliases. Aliases for pydantic models can be used� Model Config. Behaviour of pydantic can be controlled via the Config class on a model.. Options: title the title for the generated JSON Schema anystr_strip_whitespace whether to strip leading and trailing whitespace for str & byte types (default: False)

pydantic � PyPI, How to parse and read “_id” field from and to a pydantic model? I am trying (If the root was a JSON object rather than a list there would be no problem.) Using . Jan 30 · 4 min read. Pydantic Aliases. Aliases for pydantic models can be used in the JSON serialization in camel case instead of snake case as follows: from pydantic import BaseModel,

CamelCase Models with FastAPI and Pydantic, Building better machine learning feature validation using Pydantic keep track of feature names and values during feature engineering. Let's say I've trained a model using the dataframe below (it's probably not a very good model). Finally, we can convert the original dataframe to a features container� Add parse_obj_as and parse_file_as functions for ad-hoc parsing of data into arbitrary pydantic-compatible types, #934 by @dmontagu; Add allow_reuse argument to validators, thus allowing validator reuse, #940 by @dmontagu; Add support for mapping types for custom root models, #958 by @dmontagu; Mypy plugin support for dataclasses, #966 by @koxudaxi

pydantic, Settings management. One of pydantic's most useful applications is settings management. If you create a model that inherits from BaseSettings, the model initialiser will attempt to determine the values of any fields not passed as keyword arguments by reading from the environment.

Comments
  • If you use .json() for a model with a custom root type, it'll root the root object (without the '__root__': ).
  • Thanks, but that returns an object with a users property that contains the list. I will keep it in mind if there is no way to do this, that's nicer!