Underoos
Underoos

Reputation: 5200

How to validate a list of elements of specific type in marshmallow?

I have a POST endpoint in flask which takes a json data which contains a key - collections which has a list as value which in turn contains list of dictionaries containing specific keys in it.

I'm trying to validate the request.json but couldn't find a proper way to do it.

Here's the code for marshmallow schemas:

class RowSchema(Schema):
    nationalCustomerId = fields.Int(required=True)
    storeId = fields.Int(required=True)
    categoryId = fields.Int(required=True)
    deliveryDate = fields.Date(required=True, format="%Y-%m-%d")

class RequestSchema(Schema):
    combinations = fields.List(RowSchema)

I was trying to validate the request.json with RequestSchema.

The request.json I'm sending is like below:

{
    "combinations": [
            {
                "nationalCustomerId": 1,
                "storeId": 1,
                "categoryId": 1,
                "deliveryDate": "2020-01-20"
            }
        ]
}

Where am I making mistake?

This is the error I'm getting:

ValueError: The list elements must be a subclass or instance of marshmallow.base.FieldABC.

Upvotes: 3

Views: 3016

Answers (1)

Caio Filus
Caio Filus

Reputation: 714

You are missing the fields.Nested inside fields.List

class RowSchema(Schema):
    nationalCustomerId = fields.Int(required=True)
    storeId = fields.Int(required=True)
    categoryId = fields.Int(required=True)
    deliveryDate = fields.Date(required=True, format="%Y-%m-%d")

class RequestSchema(Schema):
    combinations = fields.List(fields.Nested(RowSchema))

Upvotes: 8

Related Questions