This is a small package that will ensure that your marshmallow will alway contain list.
Some times you want to ensure that your marshmallow schema will always return a list, even if the input is a single item. Just to make an API response consistent.
pip install marshmallow-always-list-field
from marshmallow_always_list_field import AlwaysListField
class MySchema(Schema):
my_list = AlwaysListField(fields.String())
If input is:
{
"my_list": "foo"
}
it will result with:
{
"my_list": ["foo"]
}
This will work with nested fields as well.
If nested field is:
class NestedSchema(Schema):
my_list = AlwaysListField(fields.String())
class MySchema(Schema):
nested = fields.Nested(NestedSchema)
and input is:
{
"nested": {
"my_list": "foo"
}
}
result will be:
{
"nested": {
"my_list": ["foo"]
}
}
Additionally you can do something like this:
class NestedSchema(Schema):
data = fields.String()
class SampleSchema(Schema):
nested = AlwaysListField(fields.Nested(NestedSchema))
assert result == {"nested": [{"data": "hello"}]}
and input is:
{
"nested": {
"data": "hello"
}
}
result will be:
{
"nested": [{"data": "hello"}]
}
pip install -r requirements.txt
pytest
MIT
Dominik Szymanski