Skip to main content

Ensure that your schema field will be a list

Project description

marshmallow-always-list-field

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.

Installation

pip install marshmallow-always-list-field

Usage

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"}]
}

Development

pip install -r requirements.txt

Testing

pytest

License

MIT

Author

Dominik Szymanski

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

always-list-field-1.0.0.tar.gz (4.1 kB view hashes)

Uploaded Source

Built Distribution

always_list_field-1.0.0-py3-none-any.whl (5.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page