Cody Blog

How to storing api keys in Android

You SHALL not save api key into version control system, but how can you manage your API keys?

There are some approaches had been discussed here. One is to saving the api key in Before add secret to this file. you need add to .gitignore file. If you already commited this file to your git. remove from git first by this command:

git rm --cache

Next, Open your and appmend a new line:

yourapikey="THIS IS API TOKEN"

Modify build.gradle and add buildConfigField for your api key

android {
    compileSdkVersion 24
    buildTypes {

        buildTypes.each {
            it.buildConfigField 'String', 'YOU_API_KEY', yourapikey

After gradle sync finished. BuildConfigVariable is auto generated to

public final class BuildConfig {
public static final String YOU_API_KEY = "12345";

Using BuildConfig.OPENWEATHER_API_KEY to reference the api key.

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.appendQueryParameter("key", BuildConfig.YOU_API_KEY);

That's it!


Related Posts