Creating a Serializer class

The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as json. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the snippets directory named serializers.py and add the following.

  1. from rest_framework import serializers
  2. from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
  3. class SnippetSerializer(serializers.Serializer):
  4. id = serializers.IntegerField(read_only=True)
  5. title = serializers.CharField(required=False, allow_blank=True, max_length=100)
  6. code = serializers.CharField(style={'base_template': 'textarea.html'})
  7. linenos = serializers.BooleanField(required=False)
  8. language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
  9. style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
  10. def create(self, validated_data):
  11. """
  12. Create and return a new `Snippet` instance, given the validated data.
  13. """
  14. return Snippet.objects.create(**validated_data)
  15. def update(self, instance, validated_data):
  16. """
  17. Update and return an existing `Snippet` instance, given the validated data.
  18. """
  19. instance.title = validated_data.get('title', instance.title)
  20. instance.code = validated_data.get('code', instance.code)
  21. instance.linenos = validated_data.get('linenos', instance.linenos)
  22. instance.language = validated_data.get('language', instance.language)
  23. instance.style = validated_data.get('style', instance.style)
  24. instance.save()
  25. return instance

The first part of the serializer class defines the fields that get serialized/deserialized. The create() and update() methods define how fully fledged instances are created or modified when calling serializer.save()

A serializer class is very similar to a Django Form class, and includes similar validation flags on the various fields, such as required, max_length and default.

The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The {'base_template': 'textarea.html'} flag above is equivalent to using widget=widgets.Textarea on a Django Form class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.

We can actually also save ourselves some time by using the ModelSerializer class, as we'll see later, but for now we'll keep our serializer definition explicit.