10

I have 2 Pydantic models (var1 and var2). The input of the PostExample method can receive data either for the first model or the second. The use of Union helps in solving this issue, but during validation it throws errors for both the first and the second model.

How to make it so that in case of an error in filling in the fields, validator errors are returned only for a certain model, and not for both at once? (if it helps, the models can be distinguished by the length of the field A).

main.py

@app.post("/PostExample")
def postExample(request: Union[schemas.var1, schemas.var2]):
    
    result = post_registration_request.requsest_response()
    return result
  
  

schemas.py

class var1(BaseModel):
    A: str
    B: int
    C: str
    D: str
  
  
class var2(BaseModel):
    A: str
    E: int
    F: str
Chris
  • 18,724
  • 6
  • 46
  • 80
Александр
  • 103
  • 1
  • 1
  • 5
  • Have you read through the docs on [discriminated unions](https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions)? That sounds like what you're asking for. – larsks Mar 19 '22 at 17:01
  • Which of your models do you want to return errors? tell me , i don't send B and E , and i send like this : { "A":"1", "C":"3", "D":"4", "F":"3" } What are you waiting for? var1 error ? var2 error ? – milad_vayani Mar 20 '22 at 02:01

2 Answers2

12

You could use Discriminated Unions (credits to @larsks for mentioning that in the comments). Setting a discriminated union, "validation is faster since it is only attempted against one model", as well as "only one explicit error is raised in case of failure". Working example below:

app.py

import schemas
from fastapi import FastAPI, Body
from typing import Union

app = FastAPI()

@app.post("/")
def submit(item: Union[schemas.Model1, schemas.Model2] = Body(..., discriminator='model_type')):
    return item

schemas.py

from typing import Literal
from pydantic import BaseModel

class Model1(BaseModel):
    model_type: Literal['m1']
    A: str
    B: int
    C: str
    D: str
  
class Model2(BaseModel):
    model_type: Literal['m2']
    A: str
    E: int
    F: str

Test inputs - outputs

#1 Successful Response   #2 Validation error                   #3 Validation error
                                          
# Request body           # Request body                        # Request body
{                        {                                     {
  "model_type": "m1",      "model_type": "m1",                   "model_type": "m2",
  "A": "string",           "A": "string",                        "A": "string",
  "B": 0,                  "C": "string",                        "C": "string",
  "C": "string",           "D": "string"                         "D": "string"
  "D": "string"          }                                     }
}                                                              
                        
# Server response        # Server response                     # Server response
200                      {                                     {
                           "detail": [                           "detail": [
                             {                                     {
                               "loc": [                              "loc": [
                                 "body",                               "body",
                                 "Model1",                             "Model2",
                                 "B"                                   "E"
                               ],                                    ],
                               "msg": "field required",              "msg": "field required",
                               "type": "value_error.missing"         "type": "value_error.missing"
                             }                                     },
                           ]                                       {
                         }                                           "loc": [
                                                                       "body",
                                                                       "Model2",
                                                                       "F"
                                                                     ],
                                                                     "msg": "field required",
                                                                     "type": "value_error.missing"
                                                                   }
                                                                 ]
                                                               }

Alternative approach would be to attempt parsing the models (based on a discriminator you pass as query/path param), as described here (Update 1).

Chris
  • 18,724
  • 6
  • 46
  • 80
1

For those looking for a pure pydantic solution (without FastAPI):

You would need to:

This approach is demonstrated below:

Credit to @Chris for his previous answer, of which this solution is based on.

from typing import Literal, Union, Annotated
from pydantic import BaseModel, Field, parse_obj_as


class Model1(BaseModel):
    model_type: Literal['m1']
    A: str
    B: int
    C: str
    D: str


class Model2(BaseModel):
    model_type: Literal['m2']
    A: str
    E: int
    F: str


# Create a new model to represent the discriminated union
ValidModel = Annotated[Union[Model1, Model2], Field(discriminator='model_type')]

# Sample data
raw_data = {
    "model_type": "m1",
    "A": "foo",
    "B": 1,
    "C": "bar",
    "D": "zap"
}

# Parse as the correct model based on `model_type`
my_model = parse_obj_as(ValidModel, raw_data)
print(type(my_model))  # <class '__main__.Model1'>
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
  • 1
    Thanks, this was a good solution. Note that if you have JSON (ie, string data) instead of a Python object, use `parse_raw_as()` instead. – dwelch91 Jun 21 '23 at 22:56