3

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?

1 Answer 1

12

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_LENGTH and CONTENT_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 called X-Bender would be mapped to the META key HTTP_X_BENDER.

So, to retrieve the API key, you need to do:

API_key = request.META.get('HTTP_AUTHORIZATION')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.