Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-Rest - How to create URL & View to extract "GET" query parameters in different formats?

I have an application that is sending a GET request in the form of /myapi/details/?id="myid".

Currently my Django-Rest server is setup to receive requests as follows:

urls.py

urlpatterns = [
  path('/details/<str:id>/', views.details.as_view()),
]

views.py

class details(APIView):
    def get(self, request, id):
        //id contains the data

This works fine when sending a GET request as /myapi/details/"myid". To try and also receive requests with /?id="myid" I added path('/details/?id=<str:id>/', views.details.as_view()), to urlpatterns, but sending the request still hits the other URL regardless of the order.

What would be the correct way to go about this? Ideally, I would like to accept both /"myid" and /?id=<str:id> formats.

like image 544
RPH Avatar asked Nov 15 '25 14:11

RPH


1 Answers

Unfortunately, that's not how you should be using query parameters.

Couple of things that would help you understand why Django (and many other frameworks) treat query parameters this way:

  1. You should use path parameters to uniquely identify resources. e.g: /details/<str: id> can return a unique Detail object having the specified id
  2. You should use query parameters to make some query to the response that the path parameters return. For example, suppose /details/<str: id> returns a list. Then, /details/103?page=1&page_size=20 can return only the first 20 items in the list of details having the id 103.

Therefore, you can only specify path parameters in Django urlpatterns.

Django stores the query parameters inside a QueryDict object (request.GET or request.query_params). You can use that to access the query parameters from the same view function as below:

class details(APIView):
    def get(self, request, id):
        page = request.GET.get('page', None)
        if page:
            # filter results based on the query parameter
        else:
            # return default results

Here, I am using a query parameter called page which is a more realistic use case.

like image 113
because_im_batman Avatar answered Nov 17 '25 08:11

because_im_batman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!