5

I'm using djangorestframework with the following code:

class RegistrationView(APIView):
   def post(self, request, format=None):
      print self.request.META.get('API_KEY')

And it returns None (other headers such as Content-Type or User-Agent are OK).

But this header definitely exists in request (this key is local-db only, so it's ok to paste it here):

Sniffer

Why?

artem
  • 16,382
  • 34
  • 113
  • 189

4 Answers4

25

The problem is with the underscore in the request header.

Set the header as API-KEY (use hyphen, not underscore) and you can capture it using

request.headers.get('HTTP_API_KEY')

The reason for this behavior is that some servers just ignore underscores.

See this related question Why do HTTP servers forbid underscores in HTTP header names

on old versions of Django: request.META.get('HTTP_API_KEY')

All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
  • This is some of the wonkiest behavior I've come across... Silently ignoring a header with no explanation or warning. – ICW Nov 20 '19 at 17:29
1

Any custom headers are prepended with HTTP_ keywords in META.

So you can try accessing the header like

request.META.get('HTTP_API_KEY')
Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
1

Because you're using both Token based and Session based auth. I presume you're testing it through the browser, in which case you're being authenticated using session, which you can actually get from the cookies, then reverse select the User and from that the Token.

Although, try testing it with Curl or any REST client. Print out request.META — first key is going to be HTTP_AUTHORIZATION.

Andrey Shipilov
  • 1,986
  • 12
  • 14
0

Sometimes preprocessing frameworks, like Varnish for caching, are set up to discard any custom headers found on the request. Maybe something like this is done on your server?

Lucas Moeskops
  • 5,445
  • 3
  • 28
  • 42