Storing and hiding the API key in an Android Studio project

Summary

If you've ever built an app which gets data from an API (e.g. TheMovieDB, The Guardian, Food2Fork, etc.), you've most likely had to acquire an API key by creating an account. The API key is then added to your project which is used to authenticate your requests.

This post will lay out the steps for one method which I've found (in many articles) for storing the API key in Android Studio. I'm not sure if this is the best way, but is one of the easiest to follow and understand for me. The gist of it is we're creating a variable which can be referenced in places wherever the API key is needed while keeping the actual key away from a platform like Github.

Steps

1. Navigate to gradle.properties (Global Properties) and add the API key anywhere in the file.
MyApiKey = "abcdefg1234567"

In the Android view, this file is located under the Gradle Scripts section When I added key, this file was completely blank:

Add the API key to this file.

2. Navigate to the
build.gradle (Module: app) for our app, add this within the android {} code block. What we're doing is creating a variable named 'MY_API_KEY' that added to the BuildConfig.java file in our project which can then be accessed anywhere in our project.

android {
    ...
    buildTypes.each{
        it.buildConfigField 'String', 'MY_API_KEY', MyApiKey
    }

3. Where the API key is needed, (for example in an Retrofit API call) use the following instead:

BuildConfig.MY_API_KEY

4. The important thing to remember (which wasn't covered in the other tutorials) is that while the gradle.properties (Global Properties) is not located in the Android project directory (and won't be added to Git), the BuildConfig.java is located under our build directory. To ensure we don't share this file, exclude it by adding the build directory to the .gitignore file with the following:

# Built application files
...
# Gradle files
.gradle/
build/

Conclusion

It doesn't take very long to implement and we'll be making those API requests in no time. As I mentioned, I'm not sure if this is the best way to hide an API key as I've read other ways of doing it. But this is the method I've been unless someone has another technique.

Comments

Popular Posts