August 13, 2021

android retrofit example

By lj007

Make your first API call using retrofit

Add retrofit and GsonConverter in your project

why to use GsonConverter here?. It will be useful for converting JsonObject directly to Java class or Kotlin class. So, we only need to pass our models.

implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.google.code.gson:gson:2.8.5'

Single instance object retrofit

What it means by single instance? We will use single instance in whole project.

   fun getRetrofitInstance() : Retrofit{
        if(retrofit == null){
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit!!
    }

Create interface for Api calling. 

This will include modelclass for login as well as response for api call

interface ApiInterface {
    @POST("LoginApi/LoginSubmit")
    fun login(@Body params: LoginParams) : Call
}

Call Api with retrofit

this is final step. You need to create instance of ApiInterface with retrofit and make api call.

        val apiInterface = ApiManager.getClient().create(ApiInterface::class.java)
        val call = apiInterface.login(LoginParams(email, password))


        //For background api call
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, t: Throwable) {
                //handle failure
            }

            override fun onResponse(call: Call, response: Response) {
                //Enjoy success
                //response.body have your LoginResponse object
            }
        })

       //For same thread api call
       val response  = call.execute()