Hiding API Keys In Android

Hiding API keys is an important and crucial practice in android. This will ensure that your API keys are not accessed by unauthorized people, reduce billing on your APIs and increase the security of your app. Let's hide API Keys in these simple steps.

Step 1 In your local.properties file add your API key i.e :

API_KEY = 1234569775555555455

Step 2 In the Build.gradle file

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

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

Step 3 Sync the project and rebuild it. Now the API Key is hidden and you can access it wherever you wish to use it for example:

    suspend fun getWeather(
        @Query("q") query : String,
        @Query("key") key : String = BuildConfig.API_KEY,
        @Query("days") days : Int = 3,
        @Query("aqi") aqi : String = "no",
        @Query("alerts") alerts : String = "yes",
    ) : WeatherResponse

Step 4 Ensure that local.properties file is excluded from the file you commit and push to Github or any other version control.