Adding optional format suffixes to our URLs

To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.

Start by adding a format keyword argument to both of the views, like so.

  1. def snippet_list(request, format=None):

and

  1. def snippet_detail(request, pk, format=None):

Now update the snippets/urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs.

  1. from django.urls import path
  2. from rest_framework.urlpatterns import format_suffix_patterns
  3. from snippets import views
  4. urlpatterns = [
  5. path('snippets/', views.snippet_list),
  6. path('snippets/<int:pk>', views.snippet_detail),
  7. ]
  8. urlpatterns = format_suffix_patterns(urlpatterns)

We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.