Create a new file tutorial/quickstart/serializers.py:
tutorial/quickstart/serializers.py
from django.contrib.auth.models import Group, Userfrom rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email", "groups"]class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ["url", "name"]
We’re using HyperlinkedModelSerializer which uses hyperlinks to represent relationships between resources. This is good RESTful design.
Open tutorial/quickstart/views.py and add the following:
tutorial/quickstart/views.py
from django.contrib.auth.models import Group, Userfrom rest_framework import permissions, viewsetsfrom tutorial.quickstart.serializers import GroupSerializer, UserSerializerclass UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by("-date_joined") serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated]class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all().order_by("name") serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated]
Instead of writing multiple views, we’re grouping common behavior into ViewSets. This keeps the code organized and concise.
from django.urls import include, pathfrom rest_framework import routersfrom tutorial.quickstart import viewsrouter = routers.DefaultRouter()router.register(r"users", views.UserViewSet)router.register(r"groups", views.GroupViewSet)# Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [ path("", include(router.urls)), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),]
By using viewsets with a router, we can automatically generate the URL configuration for our API.