Unit test Django Rest Framework API with Basic Auth

How to test an API endpoint with DRF and base64 BasicAuth

Posted March 8, 2021

If you have a Django Rest Framework API behind HTTP Basic Authentication it should look like this:

In order to test it, you will need to generate a Base64 string to pass it through the Authorization header.

Make sure you create your test user using the create_user or create_superuser functions provided by Django, otherwise your authentication backend will fail on password matching.

For this example I'm assuming you have, at least, this authentication backend in your settings: 'django.contrib.auth.backends.ModelBackend'

For more authentication unit test examples check Django Rest Framework GitHub source code directly.