Getting Started With Retrofit In Android

As a new or intermediate Android developer, getting started with Retrofit, a popular HTTP client, can seem pretty daunting. However, using this library is not as scary as it sounds. Here are four easy steps to creating your first Retrofit application.

Gradle Dependencies

First things first, include the following dependencies in your build.gradle file. These are for the retrofit library, as well as a GSON converter which is responsible for converting the JSON response from the server into your plain old Java object (POJO).

Define your model(s)

Next, we need to define the models that will be returned from the server. In this example, we will be returning a list of people that are presidents. Each person is represented in the following way:

It’s important to note that the variable names match up with the JSON representation:

If you don’t want to use the same variable names as the JSON keys, you can use the SerializedName annotation:

Since our project will be taking back a list of presidents, not just a single person, we should have a POJO for that as well:

Which has the corresponding JSON response:

Create a service interface

Next, we need to create an interface that is responsible for communicating with our API, which will look like this:

At the bottom we create a Retrofit object which has the base URL of our API, and add the GSON converter mentioned in the beginning. There is also a Call method for each call we can make to our API. In the first one we have a call that returns a presidents object, and the annotation is what defines that this is a GET request, and provides the additional path beyond the base url.

Implement the interface 

Now that we’ve defined our model, and our API calls, we can implement them in code in roughly three steps:

  1. Instantiate our Retrofit service.
  2. Instantiate the call we want to make.
  3. Implement a callback for that Call to be handled when the HTTP request is completed.

Here is what the code for that looks like. Note that a Retrofit callback has two methods: onSuccess and onFailure. In this case we just log the failure, but replace our ListView adapter in onSuccess:

And that’s it! Just like that you are getting started with Retrofit. The full sample code for this project can be found on Github.

Share this post...
Share on Reddit0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Facebook15

Leave a Reply