question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

One or another validation model base on string attribute value

See original GitHub issue

First check

  • I searched the FastAPI documentation, with the integrated search. - Integrated search doesn’t work 😦
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

from fastapi import FastAPI

class RegistrationPayloadBase(BaseModel):
    first_name: str
    last_name: str
    email: str
    password: str


class RegistrationPayloadCreative(RegistrationPayloadBase):
    type: Literal["creative"]


class RegistrationPayloadBrand(RegistrationPayloadBase):
    company: str
    phone: str
    vat: str
    type: Literal["brand"]

app = FastAPI()

@app.post("/auth/registration")
def register(
    registration_payload: Union[RegistrationPayloadBrand, RegistrationPayloadCreative]
):
    return registration_payload

Description

  • Open the browser and call the endpoint /auth/registration with body
{
"first_name":"sdf",
"last_name":"sdf",
"password":"sdf",
"email": "sdf@fsd.com"
}
  • It returns error that there are missing fields (basically all fields from brand and missing ‘type’)`.
  • Call the same endpoint with added "type": "brand" attribute
  • It returns a lot of errors as well but it also returns error that ‘type’ cannot be ‘brand’, unexpected value; permitted: 'creative'

Environment

  • OS: MacOS

  • FastAPI Version: 0.59.0

  • Python version: 3.8.2

Additional context

I tried to look for similar issues for pydantic but could not really find anything else. I also use Python for the first time in a 2 years so there might be something I’m missing. Similar thing that works in Typescript is called Discriminated unions.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
tiangolocommented, Dec 8, 2020

Pydantic will give the errors of all the models it tried to validate your data, so it will include the errors for each of the Union models that failed. It tries each one, one by one, and uses the first one that passes.

1reaction
girip11commented, Jul 22, 2020

With your definition of RegistrationPayloadBrand, the attributes company, phone, vat and type become required attributes.

So when you passed the following json, it cannot convert to RegistrationPayloadBrand because all its mandatory attributes are missing. Also it cannot be converted to RegistrationPayloadCreative since type(which is required) attribute is missing

{
"first_name":"sdf",
"last_name":"sdf",
"password":"sdf",
"email": "sdf@fsd.com"
}

If you have made the definition of the child classes as below, things should work properly

from typing import Optional
from pydantic import Field

class RegistrationPayloadBrand(RegistrationPayloadBase):
    company: Optional[str] = None
    phone: Optional[str] = None
    vat: Optional[str] = None
    type: str = Field("brand", const=True) # this is a required parameter which can take only value "brand"

class RegistrationPayloadCreative(RegistrationPayloadBase):
    type: str = Field("creative", const=True) # this is a required parameter which can take only value "creative"

Your request now has to contain type field in the JSON body.


References

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validate the Value of One Attrribute Based on Another ...
I have a user model with country and state attributes. I want to validate when the user tries to sign up, that he...
Read more >
How to Validate String Properties in Business Objects
This attribute can be used to specify the method returning Boolean value, which will be invoked in order to validate the property or...
Read more >
Model validation in ASP.NET Core MVC | Microsoft Learn
The [Remote] attribute implements client-side validation that requires calling a method on the server to determine whether field input is valid.
Read more >
Validate a value based on the value of another property
In this post, I will show how to create a helper to validate the length of a property based on the value of...
Read more >
Model instance reference - Django documentation
To create a new instance of a model, instantiate it like any other Python class: ... to run one-step model validation for your...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found