First Some History
Up until fairly recently integrating APIs into your Android application had been the wild west. Each application had their own networking and caching implementations that were generally pretty brittle and didn’t handle non optimal networking conditions terribly well.
Thanks largely to Square Inc, the innovative company bringing credit card processing for businesses to mobile phones, there is now a wealth of high quality open source libraries available that support API integration in your Android applications.
What will we learn how to do?
In this post, we will learn how to use a Retrofit, OkHttp and GSON stack in order to be able to simply and robustly integrate a REST API into your application. Using this stack we will download and parse some data from Twitch.tv. Following the steps outlined, you will be able to integrate most REST APIs into your application in just a few minutes, without writing any boilerplate code.
Lets Learn About the Stack
Retrofit
Retrofit makes it incredibly easy to download JSON or XML data from a web API and parse it into a Plain Old Java Object (POJO). For example to download a users repo information from Github all the code you need to write is:
@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user);
Additionally you would need to create the Repo POJO so that the parser knows what type of data you are expecting from that endpoint. This code can be auto-generated, more on this later.
Its just as easy to provide query parameters or do POST or HEAD requests. For instructions for how to connect with different types of APIs just see the documentation.
One of the nice features of Retrofit is the ability to add additional logic to all requests and responses. You could for instance add additional data to all request HTTP headers or intercept any unauthorized response error codes and redirect the user to your login screen.
OkHttp
OkHttp is an HTTP client for Android applications. It is efficient by default and includes support for SPDY, connection pooling, GZIP, and a HTTP response cache.
In addition OkHttp handles common networking issues automatically and silently such as retries and SSL handshake issues. Retrofit will use OkHttp automatically as its networking layer if it is present in your application.
GSON
GSON is a Java library that is used to parse JSON data into a POJO. It can also be used to convert a POJO into JSON, which in Android can be helpful as a way to store generic objects into shared preferences.
To use GSON you essentially just need to create a representative POJO of the data you wish to parse and run GSON on the data to parse it into an instance of the POJO. Its dead simple and makes parsing a breeze. To learn how to create your POJOs compatible with GSON see the documentation. Retrofit uses GSON in order to do its JSON parsing.
Lets do Some Coding!
Add the libraries to your project
- Download the jar files for Retrofit, OkHttp, and GSON.
- Drag each of the jar files into your libs folder in your project
- If using Android Studio Sync the project with gradle
Find or write an API
You probably already have an API in mind but if you are looking for a directory of APIs I recommend ProgrammableWeb. For the purposes of this tutorial we are going to be parsing a list of streams available from Twitch.tv. To see the request format see their API documentation. The basic API request to get the list of steams from Twitch.tv in JSON format is: http://api.justin.tv/api/stream/list.json
Capture Some Sample Output
In order to proceed we need some sample data that is returned from the API. In this case since it is a GET request we can just run the request in a web browser, and copy out the response such as:
[{“broadcast_part”: 4, “featured”: true, “channel_subscription”: true, “audio_codec”: “uncompressed”, “id”: “6640712464”, “category”: “gaming”, “title”: “Fnatic xPeke, Normals(ranked down) on smurf”, “geo”: “DE”, “video_height”: 1080, “site_count”: 8014, “embed_enabled”: true, “channel”: {“subcategory”: null, “producer”: true, “image_url_huge”: “http://static-cdn.jtvnw.net/jtv_user_pictures/xpeke-profile_image-a182a5fe5a8f239b-600×600.jpeg”, “timezone”: “Europe/Madrid”, “screen_cap_url_huge”: “http://static
Generate the POJOs for your data
Now for the fun part, using the sample data we just captured we are going to auto generate the POJOs that represent that data. Use jsonschema2pojo and be sure to enter in your desired package name, class name, JSON as the type, and use primitive types. For this example the generator got confused because the root of the JSON is an array and not an object; so I only pasted in the first element of the array. Some fiddling may be necessary.

Integrate the Generated POJOs Into Your Code
With the POJOs generated now we can just paste those generated classes into our project. In my sample project they are in the models package.
Use Retrofit to Download/Parse the API
Create a Rest Adapter
Creating the adapter is as simple as setting the endpoint:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.justin.tv/api")
.build();
Define the APIs interfaces
Define the interface for each endpoint you are going to connect with. In this case we are connecting to the steams endpoint with the limit and offset parameters which are used for paging the data. These are specified in the Justin.Tv API documentation.
public interface TwitchTvApiInterface {
@GET("/stream/list.json")
void getStreams(@Query("limit") int limit, @Query("offset") int offset, Callback<List<JustinTvStreamData>> callback);
}
You will notice we are expecting back a response from the endpoint that is a List of JustinTvStreamData objects, which is the POJO we auto-generated earlier. For more information on how to define this interface see the Retrofit documentation.
Create the Twitch.Tv Service
Now that we have the endpoint established and the interface defined we need to make the Twitch.Tv service that allows making requests.
TwitchTvApiInterface twitchTvService = restAdapter.create(TwitchTvApiInterface.class);
Hit the API
Making the API request is equally simple. We just need to use the service we just created.
twitchTvService.getStreams(ITEMS_PER_PAGE, pageNumber * ITEMS_PER_PAGE, new Callback<List<JustinTvStreamData>>() {
@Override
public void success(List<JustinTvStreamData> justinTvStreamData, Response response) {
consumeApiData(justinTvStreamData);
}
@Override
public void failure(RetrofitError retrofitError) {
consumeApiData(null);
}
});
What is interesting here in the fact that Retrofit will download and parse the API data on a background thread, and then deliver the results back to the UI thread via the success or failure method. Retrofit also supports just downloading on whatever thread it is called on (not shown here).
Do Something Interesting With the Data
Now that the data is in a POJO do something interesting with it!
For this demo project I display the Twitch.Tv channel image and description and used the Picasso Library to download and cache the images.

References
Open Source Sample Project
Interesting?
Do you find this sort of work interesting? Do you love quaint Bucks County Pennsylvania? Are you an amazing Android Developer? Then we would love to hear from you!