How to consume a REST-API in Android with Retrofit

android_rest_client_apiplugIn this tutorial we are going to explain building an Android application using Retrofit 2.0 REST Client to consume a REST-API generated by API Plug. You could download full source code of this Android application project at the end of the post.

To start this tutorial first you need a RESTful API. If you don’t have yet, you could automatically generate from APIPlug.

REST-API

For this tutorial we are going to use API Plug Demo API which is generated by API Plug using Sample MySQL Sakila Database.

Endpoints and Auto-Generated Swagger documentation is located in this url:
http://sandbox.apiplug.com:8000/demo/v1

On API side, we have selected 3 tables(Actor, Country, Film) and generated 3 GET endpoints for these tables. All three endpoint returns us all table values in a result array.

Android Application

In Android there are several ways to consume a REST-API. Retrofit is a type-safe HTTP Client for Android and Java which is created by Square. With the help of this library, you can easily consume any Restful API with authentication support.

In this tutorial we are going to use Android Studio and Gradle to build project.

  1. Create a new Android Application project.
  2. Add Internet permission to your AndroidManifest.xml file
    <uses-permission android:name="android.permission.INTERNET" />
    
  3. Add following dependencies for Retrofit & Picasso to your app/build.gradle file
    compile 'com.squareup.retrofit2:retrofit:2.0.1'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
    compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
  4. Sync your project to apply Gradle changes.
  5. Then you need to create your Java Object Models. Create a new package called models and add your models according to your objects on your API Response. In this demo API we have 3 objects: Actor, Country and Film.To create getter and setter methods automatically, you only define your variables then right click and press “generate getter & setter methods” menu to let Android Studio create all of them.
    Actor.java

    public class Actor {
    
        //Variables in our Actor JSON result from API
        private int actor_id;
        private String first_name;
        private String last_name;
    
    
        public int getActor_id() {
            return actor_id;
        }
    
        public void setActor_id(int actor_id) {
            this.actor_id = actor_id;
        }
    
        public String getFirst_name() {
            return first_name;
        }
    
        public void setFirst_name(String first_name) {
            this.first_name = first_name;
        }
    
        public String getLast_name() {
            return last_name;
        }
    
        public void setLast_name(String last_name) {
            this.last_name = last_name;
        }
    
    }

    Country.java

    public class Country {
    
        //Variables in our Country JSON result from API
        private int country_id;
        private String country;
    
        public String getCountry() {
            return country;
        }
    
        public void setCountry(String country) {
            this.country = country;
        }
    
        public int getCountry_id() {
            return country_id;
        }
    
        public void setCountry_id(int country_id) {
            this.country_id = country_id;
        }
    
    
    
    }

    Film.java

    public class Film {
    
        //Variables in our Film JSON result from API
        private int film_id;
        private String title;
        private String description;
        private int release_year;
        //Not all fields added from JSON, only necessary ones generated.
    
        public int getFilm_id() {
            return film_id;
        }
    
        public void setFilm_id(int film_id) {
            this.film_id = film_id;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public int getRelease_year() {
            return release_year;
        }
    
        public void setRelease_year(int release_year) {
            this.release_year = release_year;
        }
    
    
    }
  6. Also for this object models we will need simple Result objects which will store array of these objects.ActorResults.java
    public class ActorResults {
        public List<Actor> results;
    }

    CountryResults.java

    public class CountryResults {
        public List<Country> results;
    }

    FilmResults.java

    public class FilmResults {
        public List<Film> results;
    }
  7. Then you will need an API Client and an Interface for your endpoints. Create a new package called “rest” and create a new class called ApiClient.java
    public class ApiClient {
        private static APIPlug REST_CLIENT;
        private static final String API_URL = "http://sandbox.apiplug.com:8000/demo/v1/"; //Change according to your API path.
    
        static {
            setupRestClient();
        }
    
        private ApiClient() {}
    
        public static APIPlug get() {
            return REST_CLIENT;
        }
    
        private static void setupRestClient() {
    
            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
            //Uncomment these lines below to start logging each request.
    
            /*
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(logging);
            */
    
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(API_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();
    
    
            REST_CLIENT = retrofit.create(APIPlug.class);
        }
    }

    Define all your endpoints on your interface.

    APIPlug.java

    public interface APIPlug {
    
        /*
        These methods defines our API endpoints.
        All REST methods such as GET,POST,UPDATE,DELETE can be stated in here.
        */
        @GET("actor")
        Call<ActorResults> getActors();
    
        @GET("country")
        Call<CountryResults> getCountries();
    
        @GET("film")
        Call<FilmResults> getFilms();
    
    
    }
  8. Now you are ready to call your endpoints and consume the JSON files. To do this inside our fragment files we are going to call endpoint methods and show the results on a listview. According to your content you could create custom adapters for your listview and custom onclick functions for each item. You can see one of the fragments get function in here but you could find the rest of them in the source code.ActorsFragment.java get Actors Functions
    private void getActorsList() {
        final ProgressDialog loading = ProgressDialog.show(getActivity(),getContext().getString(R.string.loading_title),getContext().getString(R.string.loading_please_wait),false,false);
    
        Call<ActorResults> call = ApiClient.get().getActors();
    
        call.enqueue(new Callback<ActorResults>() {
            @Override
            public void onFailure(Call<ActorResults> call, Throwable t) {
                Log.d("APIPlug", "Error Occured: " + t.getMessage());
    
                loading.dismiss();
            }
    
            @Override
            public void onResponse(Call<ActorResults> call, Response<ActorResults> response) {
                Log.d("APIPlug", "Successfully response fetched" );
    
                loading.dismiss();
    
                actors=response.body().results;
    
                if(actors.size()>0) {
                    showList();
                }else{
                    Log.d("APIPlug", "No item found");
                }
            }
        });
    }
    
    //Our method to show list
    private void showList() {
        Log.d("APIPlug", "Show List");
    
        ActorAdapter adapter = new ActorAdapter(getActivity(), actors);
        listView.setAdapter(adapter);
    
    
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Actor clickedObj = (Actor) parent.getItemAtPosition(position);
    
                //If you have detail activity about your object define in here
                /*
                Intent detail = new Intent(getContext(), ActorDetail.class);
                detail.putExtra("actorObject", clickedObj);
                startActivity(detail);
                */
            }});
    
    }
  9. Create your other fragments like ActorsFragment and arrange your fields with your custom ArrayAdapters.
  10. Thats all, now build your project and ready to test on your Android device 🙂

As you see in simple 10 step you could create your own Android application that consumes a REST-API from scratch.

You could download full source code of this Android Demo application from https://github.com/apiplug/AndroidDemo and modify according to your project.

Click here to create your REST-API from your database with a few clicks using API Plug.

Leave a comment

Leave a Reply

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