# Android Library: Retrofit ###### tags: `Android Library` [TOC] ## Gradle >**Retrofit2 gradle** URL: https://square.github.io/retrofit/ [color=#187fce] >**RxJava2 Retrofit2 Adapter** URL: https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2 [color=#187fce] ## What is Retrofit? Retrofit is a library that communicates with the backend and returns data from a REST service. The data might be provided by several ways, I mostly get json format. >For more information about Retrofit: https://square.github.io/retrofit/ [color=red] **Gradle App:** ```java== def retrofitVersion = '2.5.0' implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion" implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion" ``` ## Retrofit Implementation Example In this example, there are: 1. An interface listing the APIs to be called 2. A class we are using as base 3. A class where we handle all requests ### Interface with all APIs Retrofit turns your HTTP API into a Java interface. >Note: @GET("all") V.S. @GET method (@Url ...) The first one is static way to call, while the second one is dynamic. It depends on what is given and that will be added to the end of the URL. [color=orange] ```java== import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Url; public interface CountriesApi { @GET("all") Single<List<Country>> getCountries(); @GET Single<List<Country>> getTest(@Url String url); } ``` ### A class using as Base ***What do we mean by this?*** >We can see that in the interface we are returning a ++**List<Country>**++. [color=Orange] ***How Retrofit knows what a Country is composed of?*** >By using ++**@SerializedName("String")**++, we can let it know what information it should get from Gson, which you get when calling API.[color=Orange] ``` java== import com.google.gson.annotations.SerializedName; public class Country { @SerializedName("name") public String countryName; @SerializedName("capital") public String capitalName; @SerializedName("region") public String regionName; } ``` ### A class that handles all requests Here we will state the base of the URL, instantiate the step2 class. ``` java== import io.reactivex.Single; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class CountriesService { public static final String BASE_URL = "https://restcountries.eu/rest/v2/"; private CountriesApi api; public CountriesService() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); api = retrofit.create(CountriesApi.class); } public Single<List<Country>> getCountries(){ return api.getCountries(); } public Single<List<Country>> getTest(String url){ return api.getTest(url); } } ```