Step 1: Keep the key out of the code
Brightline's book supplier has given you access to its catalogue API. The
lab runs a copy of it (bookapi.py; Run starts it for you), and like
almost every paid API it wants a key with each request. Whoever holds
the key can spend your money, so it must never sit in your code: code gets
shared, pasted into chats and pushed to GitHub, where bots scan new
commits for keys within minutes.
The standard arrangement:
- The key lives in an environment variable, a named value the
operating system hands to your program. Python reads it with
os.environ.get("NAME"). - On your own machine, you keep those variables in a file called
.env(open it: it is already here) and the python-dotenv library loads it.load_dotenv()copies eachNAME=valueline into the environment, without overwriting anything already set, so the real environment on a server wins. .envis listed in.gitignore, so git never commits it.
Do this
1. Add .env to .gitignore. One line, under the TODO comment.
2. Write load_settings() in books.py: call load_dotenv(), read
BOOKS_API_URL and BOOKS_API_KEY from os.environ, and if either is
missing raise a RuntimeError that names both, so whoever sets up the
program knows what to add. Return {"url": url.rstrip("/"), "key": key}.
(rstrip("/") drops a trailing slash so url + "/books" never becomes
//books.)
3. Run. It prints the settings with the key masked, then shows what the API says to a request without a key.
Starter file: .env
BOOKS_API_URL=http://127.0.0.1:8077
BOOKS_API_KEY=bl-live-4f9c2e71