How to use Retrofit
Posted on August 24, 2016 • 3 minutes • 469 words
Table of contents
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:<uses-permission android:name="android.permission.INTERNET">
Add Retrofit in your build.gradle:
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
}
In this example i will use Gson for JSON deserialization.
2) Create a new interface
public interface SampleRetrofitInterface {
@GET("/posts")
Call<List<Post>> getPostList();
@GET("/posts/{id}")
Call<Post> getSinglePost(@Path("id") int postId);
@GET("/posts/")
Call<Post> getSinglePostQuery(@Query("userId") int userId);
@PUT("/posts/{id}")
Call<Post> putSinglePost(@Path("id") int postId);
@DELETE("/posts/{id}")
Call<String> deletePost(@Path("id") int postId);
@POST("users/new")
Call<Post> createPost(@Body Post post);
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
}
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.[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
And this is my class that Gson will use to create objects from the JSON response:
public class Post {
int userId;
int id;
String title;
String body;
public Post(int userId, int id, String title, String body) {
this.userId = userId;
this.id = id;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
}
4) Use the interface
Now you can use the methods from your network interface anywhere you want.SampleRetrofitInterface api = SampleRetrofitInterface.retrofit.create(SampleRetrofitInterface.class);
Call<List<Post>> call = api.getPostList();
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>>call, Response<List<Post>> response) {
Log.i("INFO", String.valueOf(response.body().size()));
}
@Override
public void onFailure(Call<List<Post>>call, Throwable t) {
// Log error here since request failed
}
});
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 GitHubBTW: I used a similar library (Refit) in a Xamarin Project