Skip to main content

This package allows you to customize your django-rest-framework serializer i/o to make modern frontend frameworks happy.

Project description

drf-payload-customizer

License Contributing 3yourminD-Careers Stars

This package allows you to customize your django-rest-framework serializer i/o to make modern frontend frameworks happy. The following modifications are supported:

  1. Transformation: Convert all keys in API output to camelCase. Also on reception of an input on an API, transform all inputs to snake_case.
  2. Translation: Rename a key in your API schema. (works in both direction).
  3. Nullify/Balankify: Replace "" with None on output direction and vice versa in the other direction.

We introduce 3 seperate Mixins that can you can subclass your APIView from to achieve 1-3. They are:

  1. PayloadTransformationMixin: Perform transformation (1) above. Has an optional parameter PAYLOAD_TRANSFORM_NESTED (see tests) which you can set to True in your Serializer.Meta class to recursively convert all nested dictionaries. This feature only works in the output direction.
  2. PayloadTranslationMixin: Perform translation (2) above. You can specify custom mappings using a field_mappings dict in your Serializer.Meta class.
  3. PayloadNoNullOrNoneMixin: Perform nullify/blankify (3) above.

Requirements

The mixin requires you to have the following dependencies:

djangorestframework==3.8.2

We are positive it would work with other versions of Django Rest Framework as well. However, you will require Django==2.1.2 to run the unit tests.

Use it in your project

You can use all three of the mixins together like this in your project using our drf_payload_customizer.mixins.PayloadConverterMixin mixin. The mixin performs (1-3) modifications listed above. Here is how it is implemented:

class PayloadConverterMixin(PayloadTransformationMixin,
                            PayloadTranslationMixin,
                            PayloadNoNullOrNoneMixin):
    """
    Use this mixin in all of our Serializers, to convert the JSON into a
    format that is easier consumed by modern front-ends.
    """

    def to_representation(self, instance):
        return super().to_representation(instance)

    def to_internal_value(self, camel_cased):
        return super().to_internal_value(camel_cased)

Now, subclass your APIViews with PayloadConverterMixin as given below:

from drf_payload_customizer.mixins import PayloadConverterMixin

class CustomTestModelSerializer(PayloadConverterMixin, ModelSerializer):
    class Meta:
        model = TestModel
        fields = ('parama', 'param_b',)
        PAYLOAD_TRANSFORM_NESTED = True
        # The mapping is the snake_case of your expected o/p
        field_mappings = {
            'parama': 'param_a' 
        }
        
# Now your serializer would output: 
test_serializer = CustomTestModelSerializer(obj)
JSONRenderer().render(test_serializer.data)
> {'paramA': '', 'paramB': None}

# Your serializer also admits input in the same format: 
content = json.dumps({'paramA': 'testA', 'paramB': 3}).encode()
stream = BytesIO(content)
data = JSONParser().parse(stream)
serializer = CustomTestModelSerializer(data=data)
self.assertTrue(serializer.is_valid())
> True

To run tests

cd drf_payload_customizer
# Make sure you change to a virutal environment according to your project setup
python setup.py install 
pip install -r requirements.txt 
cd tests/test_app/ 
python manage.py test 

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

drf-payload-customizer-0.0.2.tar.gz (4.8 kB view details)

Uploaded Source

Built Distribution

drf_payload_customizer-0.0.2-py3.6.egg (11.7 kB view details)

Uploaded Source

File details

Details for the file drf-payload-customizer-0.0.2.tar.gz.

File metadata

  • Download URL: drf-payload-customizer-0.0.2.tar.gz
  • Upload date:
  • Size: 4.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.20.0 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.6.5

File hashes

Hashes for drf-payload-customizer-0.0.2.tar.gz
Algorithm Hash digest
SHA256 9af9b403e6eb6a99b2b3b56c0b329a0840b30cac93ce009782bc507a7a63d361
MD5 e6796f1d13c5d92f9f9edd93d998ce18
BLAKE2b-256 0edf2b0821528580f25564e97d7c5b4654c6602c75cdafdae404723342e0c803

See more details on using hashes here.

File details

Details for the file drf_payload_customizer-0.0.2-py3.6.egg.

File metadata

  • Download URL: drf_payload_customizer-0.0.2-py3.6.egg
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.20.0 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/3.6.5

File hashes

Hashes for drf_payload_customizer-0.0.2-py3.6.egg
Algorithm Hash digest
SHA256 ca9cdd045943e11fbbfb65c43db17c2b55acc22d2d3abc0c1cf7477287561cc5
MD5 5c1a78ab2feb2a957ac1684176f30420
BLAKE2b-256 dbce92d5c44a69a8b2a77b1061ab2815ff4705ecfb31e199ffd162093969a152

See more details on using hashes here.

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