CertGrid CertGrid
Best Practices·Python Automation for IT

Python API Authentication and Secrets

Getting a token into a request is one line. Keeping it out of your source, your logs, your process list and your bug reports is the actual work. This guide sends the header, then demonstrates five ways the token escapes anyway - including one that is urllib3's doing rather than yours - and builds the logging filter that stops it, starting from a version that looked right and raised on every line.

APIs and Cloud Guide 25 of 39 Intermediate

Written against the versions above. `requests` reads `~/.netrc` automatically, which surprises people; it has done so for a long time and is not new. The `netrc` module rejects a world-readable file on Unix.

Everything on this page runs on the control node. Any machine with Python 3 will do.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSControl node - every script in this path runs here2 Core4 GB50 GB

Before you start

  1. The 401, and what it tells you

  2. The header, and the token that must not be in the source

  3. A Session that carries the credential

  4. The four ways a token leaks

  5. A redaction filter, and why the obvious one breaks

  6. So redact the formatted message instead

  7. And the library that logs the URL for you

  8. A token in a file, with the permissions that implies

  9. The file the other tools already agree on

  10. Basic auth, and what it actually sends

Official sources