Interview Prep/Python for DevOps/Data formats, HTTP & REST APIs

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()
All Python for DevOps questions Roadmap: Python for automation

More on Data formats, HTTP & REST APIs