App 4: Weather App with a Real API / Build the weather app
Lesson 9 of 10
API keys and secrets
Many APIs do need a key. Keep keys out of your code: store them in an environment variable and read them with os.environ. Never upload keys to GitHub.
Key points
- os.environ.get("API_KEY")
- Add .env to .gitignore
- If a key leaks, revoke it
import os
api_key = os.environ.get("NEWS_API_KEY")
if not api_key:
raise SystemExit("Set NEWS_API_KEY first: export NEWS_API_KEY=your-key")Your turn
Practise: set a fake key with export MY_KEY=test and print it from Python.
Quiz · +10 XP
Where should an API key live?
Log in to save progress and earn XP.