Saving the API Key in gradle.properties

Refer - Complete implementation for storing API_KEY in gradle properties to avoid uploading to Github.

https://richardroseblog.wordpress.com/2016/05/29/hiding-secret-api-keys-from-git/


  1. Add gradle.properties into .gitignore file

  2. Add line in gradle.properties file API_KEY="CopyYourAPI_KEYhere"

  3. Add below line in app/build.gradle within the defaultConfig

    buildConfigField("String", "API_KEY", API_KEY)

  4. Use Key using the following statement

    String API_KEY = BuildConfig.API_KEY;

Copy this wherever you need API_KEY

It will save your efforts to add and remove API_KEY while committing code in Github.


  1. The idea of this indirection is to allow you to store API key in files that are not uploaded to the version control: gradle.properties is a local file and should not be stored under the version control, and BuildConfig is a generated class, so it will only be created at build time. It's definitely easier to store the API key somewhere as a plain String, but then you'll have to commit it to the repo.
  2. During build time, Gradle will generate the BuildConfig file to store some build-related constants. You can use buildConfigField command to instruct Gradle to add custom fields into BuildConfig. After the project is built, you can reference these constants inside your source code.

Saving the API Key in gradle.properties might not be a great idea. Using the local.properties file will be more convincing. Since local.properties file will by default be added in the git ignore file, I believe this will be a great place to add the API key.

To add the API_key in local properties you can follow these two simple steps below.

Step 1

Edit your local.properties file and add below code

sdk.dir=/Users/Library/Android/sdk
API_KEY=**Your Key**

Step 2

Edit your app-level build.gradle file and add the 'buildConfigField' inside defaultConfig as shown below.

Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())

buildConfigField "String", "API_KEY", "\"${properties.getProperty('API_KEY')}\""

Note that per this post you will need to add quotes for String types

Step 3

Sync your project with Gradle changes.

Step 4

Rebuild your project from Build->Rebuild Project.

All done!! Now you can access the key by calling BuildConfig.API_KEY

Tags:

Android

Api