-
First Check
Commit to Help
Example Codeclass RegistrationRequest(pydantic.BaseModel):
order_id: str | None
@router.post("/registration")
async def registration(
request: RegistrationRequest,
):
if request.order_id:
register_with_order(request.order_id)
else:
# This is only reached if body is '{}', if body is '' FastAPI throws 422.
register_without_order()DescriptionWe are running an API endpoint which does not expect a request model. We would like to repurpose the endpoint so that it optionally expects a JSON body. The existing logic should be available when there is no body present or the body hasn't got values for the fields. Currently, declaring a request model class makes FastAPI return HTTP 422 errors if a user posts a request without a body. Wanted SolutionWe would like to be able to have the same behaviour with empty body and with Meaning that FastAPI would be configured to proceed with execution even if the body was not found, meaning that endpoint function would get to run if all request model fields were optional. That way we could have an optional body with optional fields in our existing endpoint. Wanted Codeclass RegistrationRequest(pydantic.BaseModel):
class Options:
allow_empty = True
order_id: str | None
@router.post("/registration")
async def registration(
request: RegistrationRequest,
):
if request.order_id:
register_with_order(request.order_id)
else:
register_without_order()AlternativesNo response Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.85.1 Python VersionPython 3.10.2 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 3 replies
-
|
Wouldn’t |
Beta Was this translation helpful? Give feedback.
-
Thanks for your suggestion. Unfortunately, it still ends up in HTTP 422 in the case of empty body. |
Beta Was this translation helpful? Give feedback.
-
|
For completeness, just in case, it would be |
Beta Was this translation helpful? Give feedback.
-
|
Thanks, that does indeed achieve what we want. |
Beta Was this translation helpful? Give feedback.
-
|
Great! Thanks for reporting back and closing the issue. ☕ |
Beta Was this translation helpful? Give feedback.
-
|
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs. |
Beta Was this translation helpful? Give feedback.
For completeness, just in case, it would be
request: RegistrationRequest | None = None, the= Nonewould be key there.