- Python Snacks
- Posts
- Securing your API keys and reading them using Python
Securing your API keys and reading them using Python
See how to store your secrets both locally and on cloud platforms like AWS, GCP, and Azure.


Storing your API keys the wrong way is one of the easiest ways to leak credentials and can be costly to your organization, and it happens more often than you think.
For instance, on March 2, 2025 an active API key was found in xAI’s codebase. This API key had access to both public and unreleased models within the company.

xAI’s leaked key on GitHub
This is why it’s well worth the time to be able to take a moment and secure your keys, tokens, and credentials.
Here, I’ll provide different ways to manage your secrets for both cloud deployments and local development environments.
However, before diving in, don’t hardcode your secrets and check them into source control using a tool like git.
» Remember: your commits are your responsibility - they have your name and email on them.
Local Development
To do local development, you’re going to want to store your API keys in an environment file (.env):
export MY_API_KEY="my_key_1"
export MY_OTHER_API_KEY="my_key_2"
If you’re not sure what this file is, check out the first article from Python Snacks about using environment variables.
Remember to add the .env file to your .gitignore file - this is necessary so you don’t check your secrets into your SCM.
To load your .env file in your current session, source it:
[user@host]$ source .env # or you could use . .env
While this will work for a few API keys, when you start growing your .env file due to other environment/configurable variables, it may become unmanageable.
To combat this, leverage a cloud solution such as AWS, GCP, or Azure and call the appropriate cloud solution manager. From here, you’ll be able to dynamically fetch the specific secrets needed during runtime:
from dotenv import load_dotenv
import os
# Load .env into os.environ
load_dotenv()
# AWS
aws_secret = os.getenv("AWS_SECRET_NAME")
aws_region = os.getenv("AWS_REGION")
# GCP
gcp_project = os.getenv("GCP_PROJECT")
gcp_secret = os.getenv("GCP_SECRET_NAME")
# Azure
azure_vault = os.getenv("AZURE_VAULT_URL")
azure_secret = os.getenv("AZURE_SECRET_NAME")
Cloud solutions
Leveraging a .env file works for local development, but not in cloud environments because all of your secrets are stored in plain text, making it easy to leak.
To solve this problem, cloud providers like AWS, GCP, and Azure have services that handles storing your secrets so that you don’t need to leverage the .env file.
Amazon Web Service (AWS) Secrets Manager
AWS provides a secrets manager, which securely encrypts your secrets, supports automatic rotation, and provides centralized auditing and fine-grained access controls.
import boto3
client = boto3.client(
"secretsmanager",
region_name="us-east-1"
)
response = client.get_secret_value(SecretId="MySecretName")
print(response["SecretString"])
Google Cloud Platform (GCP) Secrets Manager
GCP’s equivalent is the Secrets Manager which lets you store and version secrets, audit access, and enforce IAM roles, ensuring compliance and easy rollback to prior versions.
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
name = "projects/my-project/secrets/MySecretName/versions/latest"
response = client.access_secret_version(
request={"name": name}
)
print(response.payload.data.decode("UTF-8"))
Azure Key Vault
Azure’s equivalent is the Key Vault which offers encrypted, centrally managed storage for secrets, keys, and certificates with HSM-backed protection, role-based access, and logging built-in.
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
vault_url = "https://my-vault.vault.azure.net/"
client = SecretClient(
vault_url=vault_url,
credential=DefaultAzureCredential()
)
secret = client.get_secret("MySecretName")
print(secret.value)
Conclusion
To sum the do’s and dont’s up:
Don’t check your secrets into source control (like Git)
Don’t hardcode your secrets into your code
Do use a .env file to store keys for local development
Do use a cloud-native solution to store secrets in the cloud
Don’t use a .env file for your cloud environment.
Happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply