Easily make REST calls in Android using Retrofit

January 07, 2019

For those who are new to Android Development, the first major complication is making a network call. If you look at the Android Developer Guide, you will immediately get confused with DownloadTask, AsyncTask and several callbacks. Fortunately there is Retrofit to save the day.


Add to this to module's build.gradle file:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'


Create the service interface:

public interface GitHubService {
    Call<String> zen();

Initialize the service in your Activity (or maybe a RestService.java class):

   Retrofit retrofit = new Retrofit.Builder()

   GitHubService service = retrofit.create(GitHubService.class);


Make your network call:

   Call<String> call = service.zen();
   call.enqueue(new Callback<String>() {
        public void onResponse(Response<String> response) {
          // Handle successful response 

        public void onFailure(Throwable t) {
            // Handle failure


Request params:

Call<List<User>> groupList(@Path("id") int groupId);

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

Request Body:

Call<User> createUser(@Body User user);

Adding headers:

@Headers("Cache-Control: max-age=640000")
Call<List<Widget>> widgetList();


Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);