Format Suffixes
Format suffixes allow your API endpoints to handle requests for different formats (like JSON or HTML) explicitly via the URL, rather than relying solely on HTTP Accept headers.
For example, a client can request http://example.com/api/users.json instead of sending an Accept: application/json header to http://example.com/api/users/.
Using format_suffix_patterns
To enable format suffixes, you append format_suffix_patterns to your URL configuration.
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from myapp import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)By default, the allowed format suffixes are determined by the format attributes on your view's configured renderers.
View Handlers
When using format suffixes, you must update your view functions or methods to accept an optional format keyword argument.
Function-Based Views
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def snippet_list(request, format=None):
# View logic...
return Response(data)Class-Based Views
from rest_framework.views import APIView
from rest_framework.response import Response
class SnippetList(APIView):
def get(self, request, format=None):
# View logic...
return Response(data)Specifying Allowed Suffixes
You can pass allowed to format_suffix_patterns to restrict which suffixes are permitted, regardless of the configured renderers.
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])