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?
Django views facilitate processing the HTTP requests and providing HTTP responses. On receiving an HTTP request, Django creates an HttpRequest instance, and it is passed as the first argument to the view function. This instance contains HTTP verbs such as GET, POST, PUT, PATCH, or DELETE.
APIView is a base class. It doesn't assume much and will allow you to plug pretty much anything to it. GenericAPIView is meant to work with Django's Models. It doesn't assume much beyond all the bells and whistles the Model introspection can provide.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post() , and instead provides actions such as .list() and .create() .
REST framework includes a set of named constants that you can use to make your code more obvious and readable. The full set of HTTP status codes included in the status module is listed below. The module also includes a set of helper functions for testing if a status code is in a given range.
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.
Basiclly this "format" parameter is used to define the output response format, like: csv, json, etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With