Search code examples
djangodjango-rest-frameworkdjango-testing

Adding custom header to DRF test APIClient


I need to add a custom header to the APIClient for a test. I have tried to follow this section of the official docs

from rest_framework.test import APIClient
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

Following the official docs results in an error because the name has hyphens This raises a syntax error because the name is not valid.

from rest_framework.test import APIClient
client = APIClient()
client.credentials(HEADER-WITH-HYPHEN='Token ' + token.key)

I also tried using from rest_framework.test import RequestsClient but this needs the url to include http which isn't possible because the server doesn't run while testing.

It also isn't possible to change the header name to something more pythonic :|


Solution

  • Apparently, this client.credentials(HTTP_header_with_hyphen=token) will evaluate to {"Header-With-Hyphen": token} in the request header.