Hide API Key for Heroku App
Assign Variable on local machine
Open Terminal or iTerm. Enter the command env. This will give you a list of the environment variables that already exist.
You can edit environment variables by using an editor like nano or vim. You can find instructions here on how to edit the script using the bash or zsh shell.
In order to store the new value in the local environment with the zsh shell then you will need to edit the .zshrc file.
When editing with vim I didn't find quitting vim very intuitive, here you can find a list of the basic quit commands.
The variable is stored in a dictionary called os.environ.
To return the value of the new variable you set you can run the following commands within the Python shell:
Or you can view the variable in the shell by running:
The Python code in my Flask Portfolio app.py file that refers to the local environment variable "Butter_CMS_Auth":
Assign Hidden Variables in Heroku
Now that the app is running on my local machine without including the API Key in my blog_blueprint.py it is time to deploy the app to Heroku. But first we must find a way to refer to the BUTTER_CMS_AUTH key in Heroku, otherwise Heroku won't know what the below line is referring to:
In Heroku under 'Settings there is a section called 'Config Variables'. Here you can assign your API Key to a variable name. You should use the same variable name as what you have previously used for the app to run locally on your Mac i.e. I used BUTTER_CMS_AUTH as the variable name.
If you want to see a list of the local variables on Heroku, you can use the printenv command when you are logged into Heroku CLI like below:
In here you should see your newly assigned variable name. When this is done you are good to go to deploy your Flask app online without having to worry about your API key being available in a public domain.
Are you struggling with hiding your API key? Did this blog post help to clear anything up for you? If you have any insights, questions or recommendations feel free to leave a comment or drop me an e-mail.