Adding endpoints for our User models

Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In serializers.py add:

  1. from django.contrib.auth.models import User
  2. class UserSerializer(serializers.ModelSerializer):
  3. snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
  4. class Meta:
  5. model = User
  6. fields = ['id', 'username', 'snippets']

Because 'snippets' is a reverse relationship on the User model, it will not be included by default when using the ModelSerializer class, so we needed to add an explicit field for it.

We'll also add a couple of views to views.py. We'd like to just use read-only views for the user representations, so we'll use the ListAPIView and RetrieveAPIView generic class-based views.

  1. from django.contrib.auth.models import User
  2. class UserList(generics.ListAPIView):
  3. queryset = User.objects.all()
  4. serializer_class = UserSerializer
  5. class UserDetail(generics.RetrieveAPIView):
  6. queryset = User.objects.all()
  7. serializer_class = UserSerializer

Make sure to also import the UserSerializer class

  1. from snippets.serializers import UserSerializer

Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in snippets/urls.py.

  1. path('users/', views.UserList.as_view()),
  2. path('users/<int:pk>/', views.UserDetail.as_view()),