I'm using django rest framework to implement a small function, which is to provide an API for our partners to access some data. The backend has already been written and I'm only writing the API to tap into it to get some data, so I'm just using function-based views to simplify things. Here's my test code:
@api_view(['GET'])
@authentication_classes((BasicAuthentication,))
@permission_classes((IsAuthenticated,))
def get_key(request):
username = request.user.username
enc = encode(key, username)
return Response({'API_key': enc, 'username': username}, status=status.HTTP_200_OK)
@api_view(['GET'])
def get_data(request):
user = request.user
API_key = request.META.get('Authorization') # the value is null
return Response({'API_key': API_key})
So the logged-in user first get an API key by calling get_key(request). Then he uses the API key to get the data. The problem is that I cannot retrieve the key that is put into the Authorization header:
headers = {'Authorization': 'yNd5vdL4f6d4f6dfsdF29DPh9vUtg=='}
r = requests.get('http://localhost:8000/api/getdata', headers=headers)
So I'm wondering how to get the header fields in django rest framework?
You need to lookup HTTP_AUTHORIZATION key instead of AUTHORIZATION because Django appends HTTP_ prefix to the header name.
From the Django docs on request.META:
With the exception of
CONTENT_LENGTHandCONTENT_TYPE, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header calledX-Benderwould be mapped to the META keyHTTP_X_BENDER.
So, to retrieve the API key, you need to do:
API_key = request.META.get('HTTP_AUTHORIZATION')
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