How do you call an API that uses OAuth2 client credentials or short-lived tokens?
AdvancedConceptData formats, HTTP & REST APIs
Answer
Fetch a token from the token endpoint, cache it with its expiry, and refresh shortly before it expires (or on a 401), instead of fetching per call.
class TokenAuth(requests.auth.AuthBase):
def __init__(self): self.token, self.exp = None, 0
def __call__(self, r):
if time.time() > self.exp - 60:
t = requests.post(TOKEN_URL, data={"grant_type": "client_credentials"},
auth=(CLIENT_ID, CLIENT_SECRET), timeout=10).json()
self.token, self.exp = t["access_token"], time.time() + t["expires_in"]
r.headers["Authorization"] = f"Bearer {self.token}"
return r
session.auth = TokenAuth()
More on Data formats, HTTP & REST APIs
How do you read and write JSON, and what are the common gotchas?BeginnerWhy must you use `yaml.safe_load` rather than `yaml.load`?BeginnerHow do you load a multi-document Kubernetes YAML file?IntermediateHow do you read and write CSV files properly?BeginnerHow do you make an HTTP request with `requests` the right way?BeginnerWhy use a `requests.Session`?Intermediate