Questions tagged [pydantic]

Pydantic is a library for data validation and settings management based on Python type hinting and variable annotations. You can use Pydantic for defining schemas of complex structures in Python.

Pydantic is a library for data validation and settings management based on Python type hinting (PEP484) and variable annotations (PEP526). It allows for defining schemas in Python for complex structures.

1612 questions
17
votes
1 answer

Best way to specify nested dict with pydantic?

Context I'm trying to validate/parse some data with pydantic. I want to specify that the dict can have a key daytime, or not. If it does, I want the value of daytime to include both sunrise and sunset. e.g. These should be allowed: { 'type':…
falsePockets
  • 3,826
  • 4
  • 18
  • 37
16
votes
2 answers

Is there any way to have multiple response models in FastAPI/OpenAPI?

I am writing an app where I need to have two completely different set of response structures depending on logic. Is there any way to handle this so that I can have two different response models serialized, validated and returned and reflect in…
Dhaval Savalia
  • 495
  • 5
  • 17
16
votes
3 answers

Pydantic constr vs Field args

I wanted to know what is the difference between: from pydantic import BaseModel, Field class Person(BaseModel): name: str = Field(..., min_length=1) And: from pydantic import BaseModel, constr class Person(BaseModel): name:…
asmartin
  • 459
  • 1
  • 3
  • 12
16
votes
1 answer

Using FastAPI & Pydantic, how do I define an Optional field with a description

For a FastAPI Pydanctic class I have these values class ErrorReportRequest(BaseModel): sender: Optional[str] = Field(..., description="Who sends the error message.") error_message_displayed_to_client: str = Field(..., description="The error…
576i
  • 7,579
  • 12
  • 55
  • 92
16
votes
2 answers

In JSON created from a pydantic.BaseModel exclude Optional if not set

I want to exclude all the Optional values that are not set when I create JSON. In this example: from pydantic import BaseModel from typing import Optional class Foo(BaseModel): x: int y: int = 42 z:…
16
votes
1 answer

How to validate a pydantic object after editing it

Is there any obvious to validate a pydantic model after some changing some attribute? Say I create a simple Model and object: from pydantic import BaseModel class A(BaseModel): b: int = 0 a=A() Then edit it, so that it is actually…
lordvlad
  • 5,200
  • 1
  • 24
  • 44
16
votes
4 answers

Python/Pydantic - using a list with json objects

I have a working model to receive a json data set using pydantic. The model data set looks like this: data = {'thing_number': 123, 'thing_description': 'duck', 'thing_amount': 4.56} What I would like to do is have a list of json…
Bill Armstrong
  • 1,615
  • 3
  • 23
  • 47
15
votes
2 answers

How to Define Class Attributes after Inheriting Pydantic's BaseModel?

In normal python classes I can define class attributes like class Example: x = 3 def __init__(self): pass And if I then do Example.x or Example().x, I get 3. When I inherit pydantic's BaseModel, I can't figure out how to define class…
Alan
  • 1,746
  • 7
  • 21
15
votes
1 answer

return pydantic model with field names instead of alias as fastapi response

I am trying to return my model with the defined field names instead of its aliases. class FooModel(BaseModel): foo: str = Field(..., alias="bar") @app.get("/") -> FooModel: return FooModel(**{"bar": "baz"}) The response will be {"bar":…
The Fool
  • 16,715
  • 5
  • 52
  • 86
15
votes
3 answers

pydantic: Using property.getter decorator for a field with an alias

scroll all the way down for a tl;dr, I provide context which I think is important but is not directly relevant to the question asked A bit of context I'm in the making of an API for a webapp and some values are computed based on the values of others…
ewen-lbh
  • 487
  • 1
  • 5
  • 17
15
votes
2 answers

Check if List is not empty with Pydantic in an elegant way

Let's say I have some BaseModel, and I want to check that it's options list is not empty. I can perfectly do it with a validator: class Trait(BaseModel): name: str options: List[str] @validator("options") def options_non_empty(cls,…
keddad
  • 1,398
  • 3
  • 14
  • 35
15
votes
1 answer

How to parse and read "_id" field from and to a pydantic model?

I am trying to parse MongoDB data to a pydantic schema but fail to read its _id field which seem to just disappear from the schema. The issue is definitely related to the underscore in front of the object attribute. I can't change _id field name…
roshii
  • 507
  • 2
  • 4
  • 10
14
votes
3 answers

FastAPI - Pydantic - Value Error Raises Internal Server Error

I am using FastAPI with Pydantic. My problem - I need to raise ValueError using Pydantic from fastapi import FastAPI from pydantic import BaseModel, validator from fastapi import Depends, HTTPException app = FastAPI() class RankInput(BaseModel): …
14
votes
3 answers

How to resolve pydantic model is not JSON serializable

I am having below pydantic models. class SubModel(BaseModel): columns: Mapping key: List[str] required: Optional[List[str]] class Config: anystr_strip_whitespace: True extra: Extra.allow …
Naxi
  • 1,504
  • 5
  • 33
  • 72
14
votes
3 answers

Defining recursive models in Pydantic?

How can I define a recursive Pydantic model? Here's an example of what I mean: from typing import List from pydantic import BaseModel class Task(BaseModel): name: str subtasks: List[Task] = [] but when I run that I get the following…
A Poor
  • 856
  • 10
  • 26