Django Rest Framework - how to get Http header information in urls.py

1.3k views Asked by At

I am making a Django-based API and here is my urls.py.

from django.conf.urls import include, url

api_version = "v1"

urlpatterns = [
    url(r'^v1/', include( "api."+ api_version +".urls", namespace=api_version )),
]

What I want to do is to retrieve API version from http accept header. I tried to use django.http.HttpRequest module, which didn't do the trick.

Is there any way to achieve this?

2

There are 2 answers

4
Jair Henrique On BEST ANSWER

You can't access request on urls.py, see: How Django processes a request

You can configure versioning on django-rest-framework and get version on request object like:

class SampleView(APIView):

 def post(self, request, format=None):
     if request.version == '1':
         return Response(status=status.HTTP_410_GONE)

Or use URLPathVersioning approach.

0
Rizwan Mumtaz On

You cannot access request in url.py, for your particular scnerio i-e for version, you can use different url for different version of your api.

like

url(r'^v1/', include("api.v1.urls")),
url(r'^v2/', include("api.v2.urls")),
url(r'^v3/', include("api.v3.urls")),