You have come up with a cool idea, decided to make an open source project, and share it on GitHub.
Most of Web APIs nowadays require developer API key, but your “Open Source” project source is made public as the name suggests.
Now the question is, how can we hide the API keys?
Add an object containing API keys and export it.
Add an entry in
.gitignore the name of file you created.
It’s easy to migrate between machines since all that’s required is to copy files from machine to machine.
Each web project requires its own copy of API keys and it’s not easy to sync unless the file is shared in a common location.
Now for a back-end language, I will use C# as an example since I am most familiar with it.
C# has a concept of partial class. Partial classes are used widely for adding new functionalities to codes that are generated by tools without the tool overwriting it.
You can use this concept to create a partial class that contains API keys exposed as properties.
First step is to create a partial class, and commit to GitHub without adding API key properties.
And then you mark the partial class file as not updatable using git.
Re-usability of partial class within a solution.
Steps involved is a bit cumbersome and it’s language dependent.
The last method is to use environment variables. Create new environment variables per each key and access it from your code.
First, create environment variables for your system (I am using Windows 10 as an example here).
In your code, simply access environment variable to fetch secret information (CredentialContext.cs).
It’s easy easily shareable/accessible from several different projects from a computer.
If you are working on a project using the environment variable from different machines (work computer and laptop at home), you need to create environment variable in each of those machine. It’s harder than just copying files from machine to machine
As a side note, I chose environment variable option for MyAnimeListSharp because the project was developed only on my laptop while working on different branches.
** Update **
Check out this Microsoft Documentation, Safe storage of app secrets during development.
There is no one method that’s better than the other. Choose a different method of hiding API keys depending on your current situation.