bauerji / flask-pydantic

flask extension for integration with the awesome pydantic package
MIT License
352 stars 56 forks source link

Question: partially populated nested object with required fields #51

Closed jakubczaplicki closed 1 month ago

jakubczaplicki commented 2 years ago

Hey all,

I am trying to understand if the behavior I am seeing is expected, a bug or misconfiguration of my setup.

The following code uses. Flask-Pydantic = "~=0.9.0"

There's an endpoint that expects the following simple payload. The address is expected to be fully populated (all fields are required).

class Address(BaseModel):
    street: str
    city: str
    region: str
    zipcode: str

class Payload(BaseModel):
    username: str
    address: Optional[Address] = None

    @root_validator
    def validate_address(cls, values):
        # address is missing from values for partially populated address fields
        if "address" not in values or not values["address"]:
            raise ValueError(f"Full address is required")
        return values

This works nicely for fully populated address and when the address is missing in the request (set to None by default).

However, when I send a partially-populated Address, the field address is missing from the payload :

Request payload :

{
"username": "foo",
"address": {
            "zipcode": "10001",
        },
    }

flask body:

{ 'username': 'foo' }

Is that expected that when a pydantic object fails to create, it will be dropped ?