Two weeks ago i wrote an Android app with connection to a REST-API. As yet i used Volley for requests. But i finally took a look at Retrofit and i think i like it. In this post i want to give a short introduction on how to use it.

What is Retrofit?

Retrofit is type-safe HTTP client for Android and Java by Square, Inc.
You can use it to simplify your API calls.

1) Create Project

Add internet permission to your AndroidManifest.xml:

Add Retrofit in your build.gradle:

In this example i will use Gson for JSON deserialization.

2) Create a new interface

In this example the baseUrl is “https://jsonplaceholder.typicode.com/”
With the annotations you can set the standard HTTP methods like (GET, POST, PUT, DELETE, PATCH, and HEAD).

For example when you call getSinglePostQuery(3) Retrofit will connect to https://jsonplaceholder.typicode.com/posts?userId=3
When you call getSinglePost(3) it will be https://jsonplaceholder.typicode.com/posts/3

3) Create Java class for parsing

This is how a typical response from https://jsonplaceholder.typicode.com/posts looks like.

And this is my class that Gson will use to create objects from the JSON response:

4) Use the interface

Now you can use the methods from your network interface anywhere you want.

The Response in onResponse will return a List of Posts.
I think Retrofit is a easy way to connect to an REST-API.

Example Project

You can find my example project on GitHub


BTW: I used a similar library (Refit) in a Xamarin Project