PSA: Please use Environment Variables

When I first started building apps that used APIs, I thought I had everything figured out. It was a simple enough task — sign up for a service, grab and copy-paste an API key, and integrate it into my Python script to fetch data. Things were going smoothly… until I made a mistake that taught me one of the most valuable lessons in programming: don’t hardcode sensitive information.
Fun Fact!
In 2019, a study by NCSU found 100,000 API keys floating on Github in a six-month span. And unfortunately, I became part of that statistic.
When I first built my project and proudly pushed it to a public Github repository, I had inadvertantly hard-coded my API key publicly on some subroutine nested folders deep. A few hours later, I received an email from the API provider that said, “Your API key has been compromised.” And they told me to (professionally) never do that sh*t again.
The Solution: Environment Variables
After a quick dive into research, I learned about environment variables, which allow you to store sensitive information like API keys separately from your codebase. This prevents accidental exposure when sharing code publicly.
Using an Weather App example, here’s how I fixed the issue:
- First, I removed the API key from my script.
- Next, I created an environment variable on my machine to store the key securely:
On macOS/Linux:
export WEATHER_API_KEY="12345abcde"
On Windows:
set WEATHER_API_KEY=12345abcde
- Finally, I updated my Python code to retrieve the API key using the os.getenv() function:
import os
import requests
API_KEY = os.getenv("WEATHER_API_KEY")
url = f"http://api.weather.com/v3/wx/forecast/daily?apiKey={API_KEY}"
response = requests.get(url)
print(response.json())
With this change, my API key was no longer hardcoded in the script. Instead, it was safely stored in the environment and retrieved when needed.
Is there a lesson in this?
That day, I learned a crucial lesson: hardcoding sensitive information in your code is risky, especially when using version control platforms like GitHub. While it’s tempting to just copy and paste an API key for the sake of convenience, the potential security risks far outweigh any benefits.
This first mistake shaped the way I approach security in coding, and if you’re working with APIs or any sensitive data, I hope you can learn from my experience before making the same error.
Pro tip 1: Always add a .gitignore file to your project and make sure it includes .env files or other sensitive configuration files. This ensures you don’t accidentally push private data to GitHub or other public repositories.
Pro tip 2: You can query with specific parameters in your Github repository using commands shown in this Github repository!
Moral of the story: think before you code and use your environment!