n.abing
n.abing

Reputation: 585

What is the "format" parameter used for in Django REST Framework views?

In the DRF documentation example found here:

class SnippetList(APIView):
    """
    List all snippets, or create a new snippet.
    """
    def get(self, request, format=None):
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The above sample has an unused format parameter in both the get() and post() methods. I have stepped through the rest_framework source and I cannot find any instance where this parameter is handed off to the get() or post() method by the dispatcher. Is this parameter required to be present in the method definition? If so, what is it used for? When is it used?

Upvotes: 8

Views: 5877

Answers (3)

Shishir
Shishir

Reputation: 337

Consider example: suppose you want the 'html' format of response which you receive your api endpoint So for this, you can easily make a query from the url itself like https://api.example.com/users/?format=html Now if your views doesn't have the parameter as format=None then this could work.

But to disable this behaviour you must turn format=None

Upvotes: 0

n.abing
n.abing

Reputation: 585

I found that the format parameter is used when you use format suffixes. So now I wanted to find out how this was used because nothing in the handler code seems to be using it but somehow it still works (magic behavior).

I went ahead and used pdb to trace execution of the view and found that APIView.initial() extracts this parameter from the kwargs and the uses it in the call to APIView.perform_content_negotiation() which selects the renderer and media type to use in the response.

Upvotes: 11

user1578226
user1578226

Reputation: 59

Basiclly this "format" parameter is used to define the output response format, like: csv, json, etc

Upvotes: 6

Related Questions