Using Django REST Framework Token Authentication with Python Requests

I’m a big fan of Django REST framework. It’s great for making an API that is used by unattended processes or third-parties. If you’re building a first-party (web) app then GraphQL (e.g. using Graphene-Python) may be a better choice, particularly if you’re using React.

If you are calling your API from a non-interactive process then you probably want to use an API token rather than a username and password. OAuth 2.0 / OIDC is usually overkill for this sort of situation. DRF has built-in support for Token Authentication that works nicely. It is basically a “Bearer” token but with a different header name.

Aside, the DRF docs are well-written. I particularly like they way they avoid confusion between authentication / authorization by instead talking about identification / permissions. Auth is confusing, even the HTTP header gets it wrong.

If you want to call your API using a token with the Python Requests library then here is a quick and easy way to do so. I’m assuming you haven’t made a custom subclass of TokenAuthentication to use the standard Bearer keyword.

When you make a request (e.g. get or post) then simply add the following to the headers (where api_token is your token):

headers={"Authorization": f"Token {api_token}"},

This is obviously quite simplistic but will get you going. If you want to make this more reusable and robust then you could subclass AuthBase and implement the custom authentication there.

This blog is treeware! If you found it useful then please plant a tree.
Donate a treeDonate a tree🌳🌳