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.
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:
/details/<str: id> can return a unique Detail object having the specified id/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.
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