July 10, 2018

How to make an API call in android Kotlin using retrofit library

     On this blog I am going to explain How to make an API call with the Help of Retrofit Library on Kotlin. Here is the steps to integrated API call using retrofit library in android Kotlin. With the help of and Interface class I am calling this API.


        First you need to add the dependency library on your app level build.gradle file.

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile('com.squareup.retrofit2:retrofit:2.1.0') {
    exclude module: 'okhttp'
}
compile 'com.squareup.retrofit2:converter-gson:2.2.0'


I am having a Constants.java class there I defiled my Base Url of my API like,


class Constants {
    companion object AppConstants {
        const val BaseUrl = "http://api.shidhin.net/";
    }
}


                      Next Step, I Created a new class ApiClient.java class, which we are used to invoke the API Call. Here is My ApiClient.java class,


class ApiClient {
    companion object {
        fun create(): ApiInterface {
            val TIMEOUT:Long = 2 * 60 * 1000
            val retrofit = Retrofit.Builder()
                    .client(OkHttpClient().newBuilder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS).writeTimeout(TIMEOUT, TimeUnit.SECONDS).build())
                    .addConverterFactory(GsonConverterFactory.create()).baseUrl(Constants.AppConstants.BaseUrl)
                    .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }

    val apiServices by lazy {
        ApiClient.create()
    }

}


                                  Next Step, I Created a new Interface ApiInterface.java , which which will  helps to API Call.  On this Class we will define the API functions. On this I have POST method with Header value, Here is My ApiInterface.java class,


interface ApiInterface {

    @POST("api/shops/AddNewShopDetails")
    @Headers("Content-Type: application/json")
    fun addShopDetails(@Body  body: JsonObject): Call<CommonServiceResponse>
}


       For the above API calls we used a class  CommonServiceResponse to parse the API response, Here is those classes, Based on the API response the structure of these class can be changed,

Class to parse addShopDetails API

class CommonServiceResponse {
    @SerializedName("status")
    public var status: Boolean? = null
    @SerializedName("message")
    public var message: String? = null
}

                    Now we added all the Class files we needed to the API Integration. Now I will show you How to invoke API calls on our Application.







API Call:  addShopDetails


val request = JsonObject()
request.addProperty("token", token)
request.addProperty("shopName", shopName)
request.addProperty("shopAddress", shopAddress)
ApiClient().apiServices.addShopDetails(request).enqueue(object : Callback<CommonServiceResponse> {
    override fun onResponse(call: Call<CommonServiceResponse>?, response: Response<CommonServiceResponse>?) {
        if (response != null && response.body() != null ) {
            
             //Here Comes the code to parse the result
} } override fun onFailure(call: Call<CommonServiceResponse>?, t: Throwable?) { Log.v("ApiFailure", "api Call Failure") } })
---------------
Thanks For Reading, Wish you a Happy Coding....

July 09, 2018

How to make API call using Retrofit on Android java class file

     On this blog I am going to explain How to make an API call with the Help of Retrofit Library. Here is the steps to integrated API call using retrofit library in Java. With the help of and Interface class I am calling this API.


        First you need to add the dependency library on your app level build.gradle file.

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile('com.squareup.retrofit2:retrofit:2.1.0') {
    exclude module: 'okhttp'
}
compile 'com.squareup.retrofit2:converter-gson:2.2.0'


I am having a Constants.java class there I defiled my Base Url of my API like,

public class Constants {
    public static final String BaseUrl = "http://api.shidhin.net/"; 
}


                      Next Step, I Created a new class ApiClient.java class, which we are used to invoke the API Call. Here is My ApiClient.java class,


public class ApiClient {
    static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(200, TimeUnit.SECONDS)
            .build();

    static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    static ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

    private static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(Constants.BaseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}


                                  Next Step, I Created a new Interface ApiInterface.java , which which will  helps to API Call.  On this Class we will define the API functions. On this I have one GET method and two POST methods(One is with Header  and another without Header), Here is My ApiInterface.java class,


public interface ApiInterface {
    @GET("api/CountryList")
    Call<CountryListResponse> getCountryList();


    @FormUrlEncoded    
    @POST("api/Login")
    Call<LoginResponse> login(@Field("username") String username, 
           @Field("password") String password);

 
    @FormUrlEncoded    
    @POST("api/shops/AddNewShopDetails")
    Call<CommonServiceResponse> addShopDetails(@Header("Authorization") String authorization, 
           @Field("name") String shopName, @Field("address") String shopAddress);
}

 On the above ApiInterface.java class I added 3 functions 1 GET method and 2 POST method (1 Post method is without passing Header value and another method is by passing Header value). Here getCountryList is a GET method,  login is a POST method without passing Header Value and  is also a POST method and on this method I am passing the Header value.

Now I need to add these functions on my ApiClient.java class. We can add the function Like,



public class ApiClient {
    static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(200, TimeUnit.SECONDS)
            .build();

    static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    static ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

    private static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(Constants.BaseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }



    public static Call<CountryListResponse> getCountryList() {
        Call<CountryListResponse> call = apiService.getCountryList();
        return call;
    }


    public static Call<LoginResponse> login(String username, String password) {
        Call<LoginResponse> call = apiService.login(username, password);
        return call;
    }
    public static Call<CommonServiceResponse> addShopDetails(String token, String shopName, String shopAddress) {
        Call<CommonServiceResponse> call = apiService.addShopDetails(token, shopName, shopAddress);
        return call;
    }
}

                    For the above API calls we used 3 class (CountryListResponse, LoginResponse and CommonServiceResponse) to parse the API response, Here is those classes, Based on the API response the structure of these class can be changed,

Class to parse getCountryList API

public class CountryListResponse {
    @SerializedName("data")
    private ArrayList<Country> data;
    @SerializedName("count")
    private int count;
    @SerializedName("message")
    private String message;

    //Here you can add Getter and Setter for this class if you need
}

public class Country {
    @SerializedName("id")
    private int id;
    @SerializedName("name")
    private String name;
}



Class to parse login API


public class LoginResponse {
    @SerializedName("data")
    private Data data;
    @SerializedName("message")
    private String message;
    //Here you can add Getter and Setter for this class if you need

public static class Data{
        @SerializedName("token")
        private String token;

       //Here you can add Getter and Setter for this class if you need
}
}


Class to parse addShopDetails API

public class CommonServiceResponse {
    @SerializedName("data")
    private Object data;
    @SerializedName("count")
    private int count;
    @SerializedName("message")
    private String message;

    //Here you can add Getter and Setter for this class if you need

}


                    Now we added all the Class files we needed to the API Integration. Now I will show you How to invoke API calls on our Application.


API Call  : getCountryList

ApiClient.getCountryList().enqueue(new Callback<CountryListResponse>() {
    @Override    public void onResponse(Call<CountryListResponse> call, 
       retrofit2.Response<CountryListResponse> response) {
        if (response != null && response.body() != null) {
            if (response.body().getData() != null) {
                ArrayList<Country> countries = response.body().getData();
                //Here Comes the code to parse the result

}
        }
    }

    @Override    public void onFailure(Call<CountryListResponse> call, Throwable t) {
        Log.v("API", "API Error : " + t.getMessage());
    }
});



API Call :  login

ApiClient.login(username, password).enqueue(new Callback<LoginResponse>() {
    @Override    public void onResponse(Call<LoginResponse> call, retrofit2.Response<LoginResponse> response) {
        if (response != null && response.body() != null) {

            //Here Comes the code to parse the result
            
        }
    }

    @Override    public void onFailure(Call<LoginResponse> call, Throwable t) {
        Log.v("API", "API Error : " + t.getMessage());
    }
});





API Call:  addShopDetails

ApiClient.addShopDetails(token, shopName, shopAddress).enqueue(new Callback<CommonServiceResponse>() {
    @Override    public void onResponse(Call<CommonServiceResponse> call, retrofit2.Response<CommonServiceResponse> response) {
        if (response != null && response.body() != null) {
            
             //Here Comes the code to parse the result

        } 
    }

    @Override    public void onFailure(Call<CommonServiceResponse> call, Throwable t) {
       Log.v("API", "API Error : " + t.getMessage());
    }
});


---------------
Thanks For Reading, Wish you a Happy Coding....