Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FASTAPI: what is the difference in setting optional fields?

i have 2 optional fields publish and ratings, here is my code

  class POST(BaseModel):
    title: str
    content: str
    published: bool = True
    rating: Optional[int] = None

They both result in optional field, so what is the difference between two?

if i try something like this, this also works

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class POST(BaseModel):
    title: str
    content: str
    published: bool = True
    rating: int = None

>Solution :

I dont think there is any difference except for the fact that by using Optional Key word we explicitly telling that this parameter Is optional both in code and swagger.

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

def foo(arg: int = 0) -> None:
    ...
On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

def foo(arg: Optional[int] = None) -> None:
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading