API Keys - Using Environment Variables in Python Projects

Secure your API key by storing it in a .env file and loading it as an environment variable using Python's dotenv module.

Learn how to securely store your sensitive API keys using environment variables in Python, eliminating common security risks. Enhance your Python AI app by implementing best practices to protect your API keys and other sensitive information.

Key Insights

  • Create a .env file to safely store sensitive data, such as the OpenAI API key, preventing accidental exposure in version control systems like GitHub.
  • Install and utilize the python-dotenv module to load environment variables in your Python applications, replacing hard-coded API keys with secured environment variables.
  • Implement JavaScript functionality to clear previous content when loading new data, enhancing user experience by preventing outdated information from displaying during new meal analyses.

Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.

This is a lesson preview only. For the full lesson, purchase the course here.

Hello, welcome back to this AI for Python course. We're building apps using the OpenAI API with Flask and JavaScript as well. My name is Brian McLean.

Thanks for sticking with it for this long. We are on to lesson 15 and we need to do a little bit of housekeeping, so to speak. So, the entire time we've been working with the AI, our API key, which is considered sensitive information, has just been sitting in the server file.

And the reason we don't want that is because what if we push this to GitHub or otherwise expose our project to public view? We wouldn't want anyone to get our API key. Obviously, the API key won't exist after this lesson's over, but still, we want to secure that kind of thing, and you'd also like to be able to secure other sensitive data, maybe passwords. And look at how we've got things set up right now.

So, we're in server 3. We're going to just stay in server 3 for this exercise, this lesson, because we're not doing much. We're not changing JavaScript or HTML and we're not doing too much. We're doing a little bit up here with the code to secure our API key, but that's it.

So, we'll just stick right here with server 03, the last file that we were working on. Okay, let's tidy up a little bit here. So, there it is.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

The OpenAI API key exposed. So, what if you made a public repo out of this? I mean, I don't. I wouldn't.

But if you did, someone could come along and go, oh, wow, free API key. So, what we're going to do is make what is called a `.env` file. It's literally a file with no name.

It just has an extension of `.env`. And then we're going to load up a module called `dotenv`, which we'll use to load the variables. So, this OpenAI key variable is going to go inside a `.env` file, and then we're going to load the environment variables. We'll just have the one, but we'll load our environment variable right back up here, and then it'll just continue to work.

So, here we are in the book. Lesson 15, Securing API Key as Environment Variable. In this lesson, we'll learn how to securely store, access, and use your API key by setting it as an environment variable.

And this is important because hard coding your API key in your Python script is a security risk, as I just mentioned. It could accidentally get exposed in version control. You could put it on GitHub where others might see it.

So, step one, we're going to make a so-called `.env` file. At the root level of your project, the same level your server files are in, we're going to make a new file called `.env`. So, to make sure you're at the root level, you can click on one of these files here, these server files. New file: `.env`. There you are inside the `.env` file.

In `.env`, paste your OpenAI key variable with no quotes or spaces. Let's come over here.

Now, let's not cut this. We'll comment it out. In case anything goes wrong or you can't get it to work, we want to be able to revert to the thing that is working.

So, let's not delete our OpenAI API key until we get the app working and get the environment variables working. Okay. So, that's the move.

You paste your API key into the `.env` file and remove quotes and spaces. Don't forget the quotes at the end. So, that's where we're at.

Step one, complete. Step two, we'll install the `dotenv` module in the terminal. Let's run a command to check if `dotenv` is already installed.

That's a good move just to know because what if you want to check to see if you've already got something installed before you install it. So, we're going to go into the terminal and type `pip show Python-dotenv`. You might have to quit your server. `pip show Python-dotenv`. Nope, not found, which is good.

We actually hope it isn't already installed, in which case it will say warning package not found `Python-dotenv`. So, that's what we want because we would like to be able to install it ourselves. Now, next, step two, number four, run this command to install `dotenv`. So, it's `pip install Python-dotenv`. Aha, looks like it worked. A new release is available.

Okay, really? Already? I don't know. I'll leave it alone. I don't want to mess with that right now.

It's saying I can install and upgrade pip. We're fine at the moment. Heck with it.

`pip install—upgrade pip`. Okay, so what it did is we did this in the other project. It uninstalls and then installs, but we're in a different project now with a different virtual environment, hence the replication of this move.

You might recall we did this very early in the story in lesson one or zero even. So, we've got our fresh version of pip. We have `Python-dotenv` installed.

It's called the `dotenv` module. So, now we're going to stay in, as I said, we'll stay in the 03 py file just because we're only making a couple changes. We don't need a whole new setup.

So, we've got `os` imported already, which is good because we need that for this move, and we're going to add one more import statement: `from dotenv import load_dotenv` like so. And I don't know what the squiggle is about. Oh, maybe.

Well, we'll see. The OpenAI squiggle is because the OpenAI key is broken, right? All right. The next move, we're going to call this `load_dotenv()` method, which is what we imported.

Load the environment variables. We just have the one, but this loads all. It's this method.

So, when you say `from dotenv import load_dotenv`, that `load_dotenv` is a method. So, we're going to call it with just adding parentheses on there. `load_dotenv()`. Okay.

Let's keep it rolling. Comment out the API key. We already did that.

When we get it working, we'll come in and delete this. The whole point is you don't want the API key visible. So, commenting it out is not enough.

We're just commenting it out now in case it doesn't work and we have to revert to the last working version. It'll be easier if we haven't deleted the API key. Call the `os.getenv` method, passing it our variable with the name in quotes.

So, let's go ahead and do that and then talk about why it's in quotes. `os.getenv`. So, the name of the variable is what we're loading. We're saving it here.

I still don't get why there's a squiggle, but we should be okay. We'll find out if there's an error somewhere. I don't think there is.

So, we're loading and now what we're doing is we're using, on the operating system, we are calling `getenv` and passing it `OPENAI_API_KEY` and loading it up from our `.env` file. The question, of course, might be why is `OPENAI_API_KEY` in quotes when variable names don't go in quotes? The answer is because the environment variables are stored as keys, key-value pairs. So, we're actually referencing a key here.

Environment variables exist as key-value pairs. So, `OPENAI_API_KEY` in quotes is a key here, not a regular variable name, hence the quotes. Now, it's just left to see if it's still working.

So, the app may still be running, but do a control + C to run it anyway. It wouldn't still be running. We're installing stuff.

Run the app. Run the app. It's not going to be still running.

We just installed packages. Okay. So, we're going to say Python.

Let's see if we can find it. There we go. All righty.

Supposedly up and going here. Refresh. Is it still working? Yep, still working.

So, here's a description of more detail on environment variables. I'll let you read how they're stored. Are they the same as Pythonic variables? No, right? They don't exist outside of the script.

And Python variables only exist in the script. These are also key-value pairs. There are just optional things to read about.

Courtesy of ChatGPT. Gave me a little rundown on environment variables. Now, I want to back up a little bit.

There's one thing from the previous lesson we can just address right now. I added one extra step for 14. So, we need to clear the results between requests.

So, once your AI meal analysis appears, let's browse to another food item. Okay. So, we got our result, ceviche.

Totally correct. Now, we're going to switch to steak. And it still says ceviche.

Because we haven't cleared the data. When the new analysis comes up, it'll clear it. But it'd be better if it just cleared immediately.

As soon as the picture shows up, we don't want the old text. The new image appears, but the previous meal's text is still here. That's kind of—it's not an error, but it is kind of buggy.

This is an easy fix, though. In the function that loads the image, we just clear the text by setting all three of those. We're just targeting those three elements and set their `innerHTML` (or their text content, for that matter) equal to an empty string.

Better `innerHTML` in case there are any tags concatenated inside here. Right? If there's a ` ` tag or any other kind of a `` tag. Any kind of tag whatsoever.

Maybe some kind of HTML entity—like a trademark symbol (™) or just anything at all that's not raw text. We use `innerHTML` to render.

And usually when you're clearing, you just say `innerHTML`. Get rid of it all. That will take care of everything in there.

Clear it all out. Including child tags. Of course, we don't have child tags.

It's just text. So, we're going to go into the JavaScript file and display the loaded image. Clear text from previous meal analysis.

So, we'll say, let's just take these three tags and just set their `innerHTML` to nothing. Save. Now, if we refresh.

Let's browse. Analyze. It works.

Now, if we choose a new image. Great. It cleared away the content.

Analyze. Notice we have to wait. Okay.

So, the next thing, and we'll do this in the next lesson, is sometimes it takes a while for the result to show up. You know, it can take long enough that you go check the console. You're wondering if you're going to get any result.

So, better would be, of course, some kind of progress indicator. A spinner would be nice. So, in the next lesson, we're going to learn how to add a spinner, which is a smidgen of JavaScript to show and hide the spinner.

And some really cool CSS. So, this is going to be mostly a CSS lesson actually coming up. Kind of advanced, cool CSS for animation.

So, we'll see you in the next lesson 16, when we add a spinner progress indicator, loading indicator to our application. So, the user has some encouragement to stick around while their meal is being analyzed. Okay.

Catch you in the next lesson.

Brian McClain

Brian is an experienced instructor, curriculum developer, and professional web developer, who in recent years has served as Director for a coding bootcamp in New York. Brian joined Noble Desktop in 2022 and is a lead instructor for HTML & CSS, JavaScript, and Python for Data Science. He also developed Noble's cutting-edge Python for AI course. Prior to that, he taught Python Data Science and Machine Learning as an Adjunct Professor of Computer Science at Westchester County College.

More articles by Brian McClain

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram