Optional Body(...) parameter? #8189
-
|
Hey folks... I have an API request (a POST) that currently takes one path var and two body vars as follows: ( I now need to add another body param. Just a string. But it's optional. I didn't see anything in the FastAPI docs that demonstrated an optional Body param, other than setting a BaseModel value to I looked at the source code and saw that I tried: But got the following exception:
Any help would be greatly appreciated. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
|
sigh Nevermind. Looks like this does it: Out of curiosity, would anybody mind elaborating on the Thanks! |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for reporting back and closing the issue. The |
Beta Was this translation helpful? Give feedback.
-
|
You changed the datatype in the answer compared to the Question, but what if the optional data is supposed to be int/float and default value is None. |
Beta Was this translation helpful? Give feedback.
-
|
@jibinmathew69 I don't understand your question. Of course this means you can not distinguise when a "myvalue: null" was sent and when directly "myvalue" was not set. I think this problem is quite extended when processing JSON input. Pydantic models "solve" it by having control over unset values (https://fastapi.tiangolo.com/tutorial/body-updates/#partial-updates-with-patch), but I guess for "primitive" types you don't have such options. Was that your question? |
Beta Was this translation helpful? Give feedback.
-
|
I'm having similar issues... I'd like to define a body as either an arbitrary dict or just no body... I've tried variants such as... but none seem to do the magic (the first two causing route confusion between Body() and Query() params, the latter just plain wrong.) Anyone know some magic I"m missing? Thanks! |
Beta Was this translation helpful? Give feedback.
Thanks for reporting back and closing the issue.
The
...means "this is required", in contrast toNone, not required, or a literal value"Foo", that means that"Foo"is the default.