maximdanilchenko/aiohttp-apispec

Validation middleware not validating top level fields when using nested dictionaries.

pzhang65 opened this issue · 0 comments

python 3.8.0
aiohttp==3.7.2
aiohttp-apispec==2.2.1

When using the same marshmallow schema to validate json body I get different results if I validate using validation_middleware versus validating using schema.loads() method in marshmallow library.

Using these marshmallow schemas:

class FieldSchema(Schema):
    nested_and = fields.List(fields.String())
    nested_or = fields.List(fields.String())

class MustSchema(Schema):
    match = fields.Dict(keys=fields.String(), values=fields.Nested(FieldSchema))
    contain = fields.Dict(keys=fields.String(), values=fields.Nested(FieldSchema))
    exists = fields.Dict(keys=fields.String(), values=fields.Nested(FieldSchema))

class SearchDeviceSchema(Schema):
    class Meta:
        unknown = RAISE
    f_and = fields.Nested(MustSchema)
    f_or = fields.Nested(MustSchema)
    f_nor = fields.Nested(MustSchema)
    object_uuids = fields.List(fields.String())
    limit = fields.Integer(description='Limit')
    offset = fields.Integer(description='Offset')

and my function:

  @json_schema(SearchDeviceSchema())
  async def search_devices(self, request):
      search_data = await request.json()
...

When POSTing a json payload, unknown fields in the top level i.e. object_error instead of object_uuids do not raise an exception. However nested fields i.e., matcHH instead of match will raise an exception.

If I try to load my request using the same schema defined as in this function:

async def search_devices(self, request):
    json_str = await request.text()
    search_data = SearchDeviceSchema().loads(json_str)
...

It will raise a ValidationError as expected no matter what level of the json dictionary.