How to keep your API keys & secrets out of your GIT repository

Rik van Velzen
1 min readApr 25, 2023

Keeping API keys and secrets out of your Git repository is crucial for security reasons, as committing sensitive information to a version control system can expose it to potential unauthorized access.

An easy to implement and much used approaches to achieve this in an Android project is by setting your API keys and secrets values in your `gradles.properties` file which is a file that won’t be pushed to your git repo:

In your gradle.properties file add the following (without the quotes!)

API_KEY="your_api_key_here"
API_SECRET="your_api_secret_here"

Now in your `build.gradle` file you can build config fields to your app by adding the following:

buildTypes {
release {
buildConfigField("String", "API_KEY", "\"${API_KEY}\"")
buildConfigField("String", "API_SECRET", "\"${API_SECRET}\"")
}
debug {
buildConfigField("String", "API_KEY", "\"${API_KEY}\"")
buildConfigField("String", "API_SECRET", "\"${API_SECRET}\"")
}
}

If you are using a newer Android Studio / Gradle plugin version you also now explicitly need to allow for using buildConfig by setting it’s value to true in the buildFeatures block of your gradle file

  buildFeatures {
buildConfig = true
}

Now after you clean/rebuild your app you can access your API key and secret values via `BuildConfig.API_KEY` and `BuildConfig.API_SECRET.

--

--