The right way of Using Third-Party API Keys in Android

3 min read

Android Development

Prologue

What should be the right way of Using Third-party API Keys in Android?

Since you have been developing android applications for some time, you might have realized the benefits of Source Code Management System like Git. When you work solely it helps, when you work within a team it helps.

So you may have thought about this question in the past.

To start our topic of discussion in detail, I would first like to add a quote by an eminent personality bill gates

It’s fine to celebrate success but it is more important to heed the lessons of failure

Good developers even good human beings keep on improving them, their ways of working, most important their perception and outlook. Our failures in life teach us more than our success in life. Experienced developers know this.

Let’s come back to our initial discussion.

Why we are emphasizing, on third-party APIs. Its because most of third party APIs like Google Maps are easy to integrate and seem free when their usage is quite low. Whenever usage of APIs increases above a particular threshold, the company which has developed APIs starts charging. (And someday my very popular idea/application will kill me if I am not careful about APIs operational cost)

Imagination

Imagine a scenario, that you have developed an open-source application or library, which can add cool functionality in the application and other developers can use it for free in their code. But since you didn’t take steps to secure your API key properly and checked in it into the public source code repository like GitHub.

The Havoc

And nightmare comes up, a lot of other developers those are using your public library, making calls to Third-party API using your API Key. and soon the third party will start charging your credit card since you have added that credit card to the third-party billing account.

The rescue

I am taking an Example of the Android App here. See the below kotlin file

/*
 * Copyright (c) 2019. Relsell Global
 */

package `in`.relsellglobal.firebasedatabasedemo

import `in`.relsellglobal.firebasedatabasedemo.pojo.CityContent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.*

/**
 * A fragment representing a list of Items.
 * Activities containing this fragment MUST implement the
 * [FrontListFragment.OnListFragmentInteractionListener] interface.
 */
class FrontListFragment : Fragment() {

    // TODO: Customize parameters
    private var columnCount = 1

    private var recyclerView:RecyclerView? = null


    private var myItemRecyclerViewAdapter : MyItemRecyclerViewAdapter? = null

    val cityContentList: MutableList<CityContent> = ArrayList()

    val APPID = "<OPEN WEATHER API KEY>"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        arguments?.let {
            columnCount = it.getInt(ARG_COLUMN_COUNT)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_item_list, container, false)
        recyclerView = view.findViewById(R.id.list);
        // Set the adapter


        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        var city = CityContent()
        city.cityName = "dehradun"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID

        cityContentList.add(city);

        city = CityContent()
        city.cityName = "new delhi"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);


        city = CityContent()
        city.cityName = "hyderabad"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);


        city = CityContent()
        city.cityName = "chennai"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);


        city = CityContent()
        city.cityName = "mumbai"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);

        city = CityContent()
        city.cityName = "mangalore"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);

        city = CityContent()
        city.cityName = "dispur"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);


        city = CityContent()
        city.cityName = "indore"
        city.apiUrl =  "http://api.openweathermap.org/data/2.5/weather?q="+city.cityName+"&appid="+APPID
        cityContentList.add(city);
        recyclerView!!.layoutManager = LinearLayoutManager(activity);
        myItemRecyclerViewAdapter = MyItemRecyclerViewAdapter(cityContentList,activity)
        recyclerView!!.adapter = myItemRecyclerViewAdapter




    }

    override fun onDetach() {
        super.onDetach()
    }

 

    companion object {

        // TODO: Customize parameter argument names
        const val ARG_COLUMN_COUNT = "column-count"

        // TODO: Customize parameter initialization
        @JvmStatic
        fun newInstance(columnCount: Int) =
            FrontListFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_COLUMN_COUNT, columnCount)
                }
            }
    }
}

More specifically see the line

   val APPID = <Open weather api key>

now open local.properties file and add your third party API key there. This file is already added into .gitignore file and doesn’t go to remote git repository whenever a commit/push is made.

openweather_data_api_key=<key value>

Besides above you want to access your API inside your kotlin files. But before doing that you need to create buildConfigField in your app level build.gradle file.

defaultConfig {
        .....
        buildConfigField "String", "OPENWEATHERDATA_API_KEY", "\""+localProperties['openweather_data_api_key']+"\""
       ....
    }

To access buildConfigField inside your kotlin file, you use property from the autogenerated BuildConfig.java file.

So your kotlin file snippet will become

val APPID = BuildConfig.OPENWEATHERDATA_API_KEY

Now, you can safely commit /push your file changes into a remote git repository without worry about API keys being published.

Conclusion

Congrats you have come up to this and investing time in growing yourself.

Remember friend nothing in this world is free. 🙂 Now you know The right way of Using Third-Party API Keys in Android

Thanks for reading. Feel free to check out my other blogs my team, on Android development topics.

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *