Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the DRF Format option mean

I am using DRF for the first time and I would like to know what the "format" in the following code snippet from their website do:

class CommentList(APIView):
    def get(self, request, format=None):
        # do stuff...

    def post(self, request, format=None):
        # do stuff...

I read the docs, but I am not sure how it works still. Can someone enlighten me with an example? Thanks

like image 515
AKJ Avatar asked Sep 02 '25 03:09

AKJ


1 Answers

For example,

Suppose their is an APIView with following code :

class HelloAPIView(APIView):
    def get(self, request, format):
        # do stuff...

    def post(self, request, format):
        # do stuff...

And endpoint url for HelloAPIView is :


http://example.com/api/users

Now if u want the data in response to be in json format then the URL you would access will be like


http://example.com/api/users.json

So when you access urls like above , then value " json " will be passed as 3rd argument (1st is self , 2nd is request and 3rd is format) to get() or post() methods of HelloAPIView.

So basically format parameter is used to define in which format you want the response.

For more details refer

  1. https://www.django-rest-framework.org/api-guide/format-suffixes/
  2. https://www.django-rest-framework.org/tutorial/2-requests-and-responses/#adding-optional-format-suffixes-to-our-urls
like image 140
Prateek Gupta Avatar answered Sep 05 '25 08:09

Prateek Gupta