Creating an endpoint for the highlighted snippets

The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.

Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.

The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.

Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own .get() method. In your snippets/views.py add:

  1. from rest_framework import renderers
  2. from rest_framework.response import Response
  3. class SnippetHighlight(generics.GenericAPIView):
  4. queryset = Snippet.objects.all()
  5. renderer_classes = [renderers.StaticHTMLRenderer]
  6. def get(self, request, *args, **kwargs):
  7. snippet = self.get_object()
  8. return Response(snippet.highlighted)

As usual we need to add the new views that we've created in to our URLconf.We'll add a url pattern for our new API root in snippets/urls.py:

  1. path('', views.api_root),

And then add a url pattern for the snippet highlights:

  1. path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()),