https://www.django-rest-framework.org/tutorial/1-serialization/
Curl alternative
pip install httpie
http http://127.0.0.1:8000/snippets/-
Initial setup
-
Created serializers.py - way to serialize/deserialize instances.
serializers.Serializer- manually defining properties, later we can useModelSerializer- AFter we created model instance - we can serialize into bytes.
serializer = SnippetSerializer(instance) content = JSONRenderer().render(serializer.data)
- And also deserialize it
stream = io.BytesIO(content) data = JSONParser().parse(stream) serializer = SnippetSerializer(data=data) serializer.is_valid() serializer.validated_data # ordered dict serializer.save() # saves instance in the database
- This works with multiple instances too:
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
-
Moving to ModelSerializer - just like Form has ModelForm, Serializer has ModelSerializer = code is more concise
- We can print the actual code of model serializer:
print(repr(SnippetSerializer()))
- We can print the actual code of model serializer:
-
Writing regular Django views using our Serializer
-
Part 2 - Introduction to
RequestandResponseclasses.Responserenders content based on requested content-type.- Use constants for http status codes rather than numeric values!
-
Rewrite views to use mixins and Request response classes.
-
Add
format_suffix_patterns- this helps with specifying whether we want response in json or browsable api format (html)
-
Part 3
- Mixins replace most of the basic verbose functionality. See each
views.pyfile
- Mixins replace most of the basic verbose functionality. See each
- Code snippets are always associated with a creator.
- Only authenticated users may create snippets.
- Only the creator of a snippet may update or delete it.
- Unauthenticated requests should have full read-only access.
def perform_create(self, serializer):
serializer.save(owner=self.request.user)Also nice to notice - adding list of ids from snippets that user has created. These are the FK's in snippets table,
representing ID of user.
# User serializer
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())This field will be only used when GETting data, it will be omitted on PUT.
owner = serializers.ReadOnlyField(source='owner.username')Alternative: CharField(read_only=True)
permission_classes = [permissions.IsAuthenticatedOrReadOnly]- will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access (still will display data).
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]