Intermediate level · Module 1: Python for AI Applications · Lesson 2 of 3
Secrets and Configuration
Keep API keys out of code and manage settings safely.
In this lesson you will
- Store API keys in environment variables or secret files
- Separate configuration from code
Key concepts
API keyenvironment variable.env file and .gitignoreconfiguration
The lesson
An API key is like a password that also spends money. Anyone who finds it can use the service on your account.
Never write keys in code or share them in chats. Read them from environment variables (os.environ["API_KEY"]) or a local .env file listed in .gitignore so it is never committed.
Keep other settings — model name, limits, file paths — in a configuration file, so they can change without editing code.
Step by step
- Create a .env file with a dummy key.
- Add .env to .gitignore.
- Read the key in Python from the environment.
- Move settings to a configuration file.
Practice activity
Refactor the practice script so it contains no secrets and reads settings from configuration.
Expected result: A script and repository with no secrets and a clear configuration file.
Check your understanding
-
Why are leaked API keys dangerous?
Show answer
Anyone can use the service on your account and spend your money.
-
How do you stop a .env file being committed?
Show answer
List it in .gitignore.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.