Resource mentioned in this lesson: Your Python Coding Environment on Windows: Setup Guide
Securely Storing Your API Key
00:00 In this lesson, you’ll learn how to securely store your API key. Now, a note to start with, never ever hard-code your API key directly into your Python scripts and never ever commit it to version control.
00:17 I’ll be repeating this message later in the course because this is very important. So how do you set your environment variable? Well, that depends on which operating system you’re on.
00:28
So Linux or macOS, you use the export command and then the name of the environment variable. So OPENAI_API_KEY, all in uppercase, that is important.
00:40
And then equals and then between quotation marks, your API key. So where it says your-API -key here, that’s where you’ll paste the key you created in the previous lesson.
00:51
For Windows, it’s a different instruction. It’s $env:OPENAI_API_KEY equals and then your API key.
01:04
Now, the openai library reads this variable automatically, but only if you spelled it correctly. So again, OPENAI_API_KEY, all in uppercase. If you spelled it differently, it won’t work.
01:21 The instructions to set the environment variable only set that variable for the duration of your current shell session. That is important. In other words, when you close your shell, your key will be lost.
01:34 Therefore, please, please, please store your key safely locally so you can use it in future sessions. Now, what I mean by that is you’ll need to repeat the instructions to set the environment variable as you’ve done on the previous slide.
01:50 So therefore, you’ll need to have this key available somewhere in a password manager, for example. That sounds a bit annoying. I agree. So therefore, there’s actually a way to avoid it. You can make your variable persistent.
02:03 So you can make your environment variable persistent. And again, it depends on which operating system you’re on. If you run Windows, I would recommend you follow the link to the Real Python tutorial. There’s also a link at the very end of this course.
02:18 For Linux and macOS, you can add the environment variable to the configuration file for your specific shell. So that’s personally the option I’ve chosen. There’s a third one.
02:30
You can use the .env file. You will cover that later in the course. But for that to work, you actually need a virtual environment first. So in the next lesson, let’s set up your virtual environment.
Become a Member to join the conversation.
