Search code examples
pythonpython-3.xflaskflask-restfulmarshmallow

Troubles with validating nested values


I am looking to add validation to my api endpoint using Marshmallow.

I am running into the problem of how to get this chunk properly validated. The end goal is to make sure impressions is a positive number.

I would greatly appreciate any help or insight you can provide. First time using Marshmallow.

Sample Json:

{
    "mode": [
        {
            "type": "String",
            "values": {
                "visits": 1000,
                "budget": 400
            },
            "active": true
        }
    ]
}

Sample code attempting to validate

class ValidateValues(BaseSchema):
    visits = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])
    budget = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])


class ModeSchema(BaseSchema):
    type = fields.String(required=True)
    active = fields.Boolean(required=True)
    values = fields.Nested(ValidateValues)


class JsonSchema(BaseSchema):
    mode = fields.List(fields.Dict(fields.Nested(ModeSchema, many=True)))

Current result

{
    "mode": {
        "0": {
            "type": {
                "key": [
                    "Invalid type."
                ]
            },
            "values": {
                "key": [
                    "Invalid type."
                ]
            },
            "active": {
                "key": [
                    "Invalid type."
                ]
            }
        }
    }
}

Solution

  • You're just using a list of Nested fields. No need for Dict, here.

    And no need for many=True since you're putting the Nested field in a List field.

    Try this:

    class JsonSchema(BaseSchema):
        mode = fields.List(fields.Nested(ModeSchema))