Hide your secret API keys!

Photo from Medium

Why should you hide your API keys?

If you are working on a project and want to make the code public (on GitHub) then it's very important that you hide the secret API key before pushing it to GitHub.

Your API keys are like your passwords that you shouldn't tell anyone because using your API keys they would be able to control your website and make changes to it or worse, delete it.

I'll show you a simple way of hiding it using Django.

You need the following 3 files:

A) config.py - This is where we will store our Key.

image.png

B) settings.py - Where the key originally is. (it might differ for you based on the stack you're using)

image.png

We need to import the config from the folder which is reddit using the command from reddit import config and then for the secret we can access it using the command config.SECRET_KEY

Remember, this is case sensitive and will not work if the cases don't match exactly. And remember to import from the correct folder.

C) .gitignore - This is a very crucial file, this is where we add the files, folders that we want to exclude from being uploaded to GitHub.

image.png

There are a lot of other files, folders that you can include depending on the language you're using as the editor and stack you use may create residual files. Check out gitignore.io where you can specify the language you're using and it generates the .gitignore file for you which you can paste in your project files. How awesome is that?

image.png

This is a raw file so you can easily copy paste the details in your own .gitignore file. image.png

Did I mention it is opensource? So you can tinker with the website and make it your own. You can also add/edit the templates. Go try it out!

After you're done with the above steps, now it's time to add all the modifications using git add -A

You'll notice the files, folders that you added in .gitignore file is not in the list of files that is added. .gitignore file however will be added and that's completely safe.

Commit the changes and push the code on GitHub!

Give yourself a pat on the back because you just secured your project. Great job!

p.s. I am aware of the another method of environment variables but I believe the above method is the most efficient, so I explained only about this one. Let me know if you're interested in learning more about using the environment variables to hide your API keys and I shall deliver.

Hope you enjoyed this post! If you happen to like it, feel free to share. You can also follow me on Twitter on my coding journey.

No Comments Yet