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
- Python3.14.4
- Control nodeUbuntu 26.04 LTS
- Managed hostsRHEL 10.0
- requests2.34.2
- paramiko5.0.0
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
- TimeAbout 20 min
- Reviewed24 August 2026
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.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
Before you start
- guide 7 - where the token comes from.
- guide 20 -
os.openwith a mode, used here. - guide 6 - the handler this filter attaches to.
-
The 401, and what it tells you
-
The header, and the token that must not be in the source
-
A Session that carries the credential
-
The four ways a token leaks
-
A redaction filter, and why the obvious one breaks
-
So redact the formatted message instead
-
And the library that logs the URL for you
-
A token in a file, with the permissions that implies
-
The file the other tools already agree on
-
Basic auth, and what it actually sends