Is there a safe way to manage API keys?

1. Store api keys in an xml file

Put xml file “api_keys.xml” in the directory “res/values/”.

api_keys.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="THE_MOVIE_DB_API_TOKEN">XXXXX</string>
</resources>

use api keys in java code

context.getString(R.string.THE_MOVIE_DB_API_TOKEN);

2. Store API keys with help of Gradle and the gradle.properties file

Example_0
Example_1

Add the following line to [USER_HOME]/.gradle/gradle.properties

For Windows OS, an example for Denis user:

C:\Users\Denis\.gradle

gradle.properties

MyTheMovieDBApiToken="XXXXX"

Add the following code to the build.gradle file

build.gradle

apply plugin: 'com.android.application'

android {
    ...

    defaultConfig {
        ...
    }
    buildTypes {
        release {
            ...
        }
    }
    buildTypes.each {
      it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', MyTheMovieDBApiToken
    }
}

use api keys in java code

BuildConfig.THE_MOVIE_DB_API_TOKEN)

3. Store API keys with help of gradle and the system path variable

Example_0

Add new system PATH variable THE_MOVIE_DB_API_TOKEN=”XXXXX”:

For Windows OS:

  • open system
  • advanced system settings
  • environment variables
  • add new variables to the user variables

Add the following code to the build.gradle file

build.gradle

apply plugin: 'com.android.application'

android {
    ...

    defaultConfig {
        ...
    }
    buildTypes {
        release {
            ...
        }
        buildTypes.each {
            it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', "\"$System.env.THE_MOVIE_DB_API_TOKEN\""
        }
    }
}

use API keys in java code

BuildConfig.THE_MOVIE_DB_API_TOKEN

Link to my gist on github

Leave a Comment