APIs and Async · HTTP and JSON · lesson 4 of 12
Authentication headers
about 14 minutes · free · runs in your browser
Proving who you are
Most APIs want a token, and most want it in the Authorization header as a bearer
token:
headers = {"Authorization": "Bearer " + token}
r = requests.get(url, headers=headers)
Without it you get 401 Unauthorized — "I do not know who you are". With a valid token but insufficient rights you get 403 Forbidden — "I know who you are, and no".
Never hardcode a token in source. Read it from the environment or a config file, and keep
it out of version control. The fake service accepts the token exposed as
requests.TOKEN, which stands in for that.
Your turn: write fetch_secret(token) returning the secret field when the token
is valid, and None on a 401 — without raising.
You start from this, and edit it in the browser:
import fake_requests as requests
URL = "https://api.pylearn.dev/secure"
def fetch_secret(token):
# Return the secret, or None when the token is rejected.
pass