Making sure our URL patterns are named

If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.

  • The root of our API refers to 'user-list' and 'snippet-list'.
  • Our snippet serializer includes a field that refers to 'snippet-highlight'.
  • Our user serializer includes a field that refers to 'snippet-detail'.
  • Our snippet and user serializers include 'url' fields that by default will refer to '{model_name}-detail', which in this case will be 'snippet-detail' and 'user-detail'.

After adding all those names into our URLconf, our final snippets/urls.py file should look like this:

  1. from django.urls import path
  2. from rest_framework.urlpatterns import format_suffix_patterns
  3. from snippets import views
  4. # API endpoints
  5. urlpatterns = format_suffix_patterns([
  6. path('', views.api_root),
  7. path('snippets/',
  8. views.SnippetList.as_view(),
  9. name='snippet-list'),
  10. path('snippets/<int:pk>/',
  11. views.SnippetDetail.as_view(),
  12. name='snippet-detail'),
  13. path('snippets/<int:pk>/highlight/',
  14. views.SnippetHighlight.as_view(),
  15. name='snippet-highlight'),
  16. path('users/',
  17. views.UserList.as_view(),
  18. name='user-list'),
  19. path('users/<int:pk>/',
  20. views.UserDetail.as_view(),
  21. name='user-detail')
  22. ])