django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

[BUG] Requests with single Body() aren't properly parsed

Open stephane opened this issue 3 years ago • 3 comments
trafficstars

Describe the bug

It would very convenient to use Body() when the schema contains only one argument but in this case, django-ninja doesn't apply the right validation path.

A view with a single body, such as:

@api.post("/body")
def create_body(request, start: int = Body(...)):
    return [start]

won't be properly parsed by the BodyModel class because the test against _single_attr will embed the dict into another dict.

I created a branch with a unit test to describe the issue. https://github.com/stephane/django-ninja/commit/9dd5f376b7872c4c0c20128f7112c5ec70cd4945

I try to fix the issue by testing if the model instance has__schema_cache__ attribute but it doesn't seem to be the right approach.

Versions

  • Python version: 3.10
  • Django version: 4.0
  • Django-Ninja version: be500ab

stephane avatar Mar 28 '22 14:03 stephane

same issue too

hongdoojung avatar Jun 27 '22 11:06 hongdoojung

@stephane @hongdoojung

what's the expected body ?

this:

{"start": 4}

or

4

vitalik avatar Jun 27 '22 13:06 vitalik

For me, it's:

{"start": 4}

but if you ask the question it's certainly because it could be confusing or because you want to handle the both inputs.

FastAPI handles a boolean called embed to select the appropriate behavior https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter

stephane avatar Jul 19 '22 20:07 stephane