Retrofit Love Working With Apis On Android Sample
Retrofit Love Working With Apis On Android Sample
Retrofit Love Working With Apis On Android Sample
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
2015 - 2016 Future Studio
Contents
Introduction . . . . . . . . . . . . . .
What Topics Are Waiting for You?
Who Is This Book For? . . . . . .
The Source Code . . . . . . . . . .
Retrofit Book for Version 1.9 . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
i
i
ii
iii
iii
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
1
1
2
2
5
6
Outro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10
Introduction
Due to the popularity of the Retrofit blog post series published in the Future Studio blog, weve
decided write a book on Retrofit. Were delighted about the amazing popularity of the Retrofit series!
Thanks a lot for all of the positive feedback, comments and encouragement! Your kind words
go a long way and keep us motivated to publish more content on Retrofit.
This is the second edition of our Retrofit book. Weve updated the content including code examples
to address Retrofit 2. The first edition was completely geared towards Retrofit 1. If youre using
Retrofit 1 and want to read the first edition of this book, please visit this books extras on Leanpub
to download the package with PDF, mobi and epub files.
Within this book, we keep the kind of techy style from the tutorials to make this book a great resource
for every developer working with Retrofit.
Introduction to Retrofit
Quick Start Guide to jump right into Retrofit
Create a Sustainable Android REST Client
Extensive manipulation and customization of requests
Comprehensive overview of response converters and data mapping
Handling Authentication on Android (Basic, Token, OAuth, Hawk)
Advanced File Handling, like File Up- and Download
How to handle errors in your Android app
Debug requests and response using logging
App release preparation including ProGuard configuration
Introduction
ii
the first client to perform a request against the GitHub API (learning by doing is an effective method
:)).
Once we managed the jumpstart, we show you the details about Retrofits requests: how to perform
them synchronous and asynchronous and how to manipulate requests to your personal needs, like
adding request parameters, path parameters, request payload and a lot more!
Well also walk you through Retrofit responses, show you how to change the response converter and
how to mock an API on Android itself.
Knowing the basics about Retrofit, we touch a common use case: authentication. Besides basic and
token authentication, well explain how to use Retrofit for OAuth (including OAuth 2) and how to
use OAuths refresh token to get back a valid access token.
File handling can be kind of tricky, so lets take the road together! We guide you through file upand downloads with Retrofit and show the actions required to send and receive different types of
files like images and compressed packages (e.g. ZIP).
Last but not least: once you get your app (using Retrofit) out the door, you need to prepare the
release for Google Play. This chapter digs into the correct configuration of ProGuard for Android
projects integrating Retrofit and presents examplary rules to keep your app working correctly after
distributing via Google Play.
Rookie
If youre just starting out with Retrofit (or coming from another HTTP library like Android
Asynchronous Http Client or even Volley) this book will show you all important parts on how
to create sustainable REST clients on Android. The provided code snippets let you jumpstart and
create your first successful API client within minutes!
Expert
If youve already worked with Retrofit, youll profit from our extensive code snippets and apply the
learnings to your existing code base. Additionally, the book illustrates various use cases for different
functionalities and setups like authentication against different backends, request composition, file
up- and downloads, etc.!
Introduction
iii
https://leanpub.com/user_dashboard/library
Retrofit Overview
Retrofit is a type-safe REST client for Android and Java.
Retrofit abstracts your REST API into Java interfaces. Youll use annotations to describe your
individual API endpoints and their HTTP requests. Support for URL parameter replacement (like
query and path parameter) is integrated by default, as well as functionality for form-urlencoded
and multipart requests. You can of course execute requests using the HTTP methods GET, POST, PUT,
PATCH, DELETE. Anyway, this is literally just the tip of the iceberg and theres a lot more to discover
behind Retrofits scenes.
or runnables or even lovely AsyncTasks definitely causes a lot pain in the a**! Think about the pain
and effort you need to put into your own implementation.
Youll safe yourself a lot of time and anger when leveraging a well thought-out and tested library
like Retrofit. If you scrolled through the outline of this book, youve already an impression about the
functionality and flexibility that comes with Retrofit. Benefit from the library and put your work to
pieces where your attention is actually needed!
A common practice is, to add your app permissions as the first elements in your manifest file. The
following snippet is an excerpt from the sample project you can find within the extras of this book
on Leanpub.
https://developer.android.com/sdk/index.html
1
2
3
4
5
6
7
dependencies {
// Retrofit & OkHttp
compile 'com.squareup.retrofit2:retrofit:2.1.0'
}
pom.xml
1
2
3
4
5
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.1.0</version>
</dependency>
Sync your Gradle or Maven project to import the required packages for Retrofit. Retrofit 2 doesnt
ship with an integrated response converter anymore. We need to manually add the desired response
converters as a dependency to our project. The following section will show you how to add Gson
for JSON response mapping to your project.
dependencies {
// Retrofit & OkHttp
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
pom.xml
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.1.0</version>
</dependency>
Once again, synchronize your project to import the Gson converter for Retrofit. In the following,
youll learn how to define a service interface to map a given API endpoint.
The snippet above defines a Java interface called GitHubService having only one method reposForUser(). The method and its parameters have Retrofit annotations which describe the behavior
of this method.
The @GET() annotation explicitly defines that a GET request will be executed once the method gets
called. Further, the @GET() definition takes a string parameter representing the endpoint url of your
API. Additionally, the endpoint url can be defined with placeholders which get substituted by path
parameters.
The method signature contains a @Path() annotation for the user parameter. This @Path annotation
maps the provided parameter value during the method call to the path within the request url. The
declared {user} part within the endpoint url will be replaced by the provided value of username.
Well catch up path parameters in more detail in a later chapter.
The snippet above only describes how to define your API on the client side. Thats fine for now.
Well have a look at the practical example in a second. There, were going to execute the actual API
request.
Service Generator
The ServiceGenerator is our API clients heart. In its current state, it only defines one method to
create a basic REST client for a given class/interface which returns a service class from the interface.
Here is the code:
https://github.com/bkiers/retrofit-oauth/tree/master/src/main/java/nl/bigo/retrofitoauth
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
The ServiceGenerator class uses Retrofits Retrofit-Builder to create a new REST client with the
given API base url (BASE_URL). For example, GitHubs API base url is located at https://api.github.com/
and you must update the provided example url with your own url to call your API instead of
GitHubs.
The serviceClass defines the annotated class or interface for API requests. The following section
shows the concrete usage of Retrofit and how to define an exemplary GitHub client.
Why Is Everything Declared Static Within the Servicegenerator?
You might wonder why we use static fields and methods within the ServiceGenerator class.
Actually, it has one simple reason: we want to use the same OkHttpClient throughout the app to just
open one socket connection that handles all the request and responses including caching and many
more. Its common practice to just use one OkHttpClient instances to reuse open socket connection.
That means, we either need to inject the OkHttpClient to this class via dependency injection or use
a static field. As you can see, we chose to use the static field. And because we use the OkHttpClient
throughout this class, we need to make all fields and methods static.
Retrofit in Use
Ok, lets use an example and define a REST client to request data from GitHub. First, we have to
create an interface and define the required methods.
GitHub Client
Well use the already defined GitHubService interface from above that has only one method
to request the repositories for a given user. Remember that were replacing the path parameter
placeholder ({user}) with the actual value of user when calling this method.
1
2
3
4
The interface above defines a GitHubRepo class. This class includes the required object properties
to map the response data. For illustration purposes, we just define the repositorys id and name
properties. GitHubs API response for this endpoint has a lot more data, but is sufficient to show
you how things work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
With regard to the previous mentioned JSON mapping: the created GitHubService defines a method
named reposForUser with the return type List<GitHubRepo>. The List<GitHubRepo> is wrapped
into a Call. Well cover the Call within the next chapter. For now its ok to know that you need
wrap your response into a call object.
If an appropriate response converter is present, Retrofit ensures that the servers JSON response gets
mapped correctly to Java objects (assuming that the JSON data matches the given Java class).
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Change base url to GitHub API
ServiceGenerator.changeApiBaseUrl("https://api.github.com/");
// Create a simple REST adapter which points to GitHubs API
GitHubService service =
ServiceGenerator.createService(GitHubService.class);
// Fetch and print a list of repositories for user fs-opensource
Call<List<GitHubRepo>> call = service.reposForUser("fs-opensource");
call.enqueue(new Callback<List<GitHubRepo>>() {
@Override
public void onResponse(
public void onResponse(Call<List<GitHubRepo>> call,
Response<List<GitHubRepo>> response) {
if (response.isSuccess()) {
for (GitHubRepo repo : response.body()) {
Log.d("Repo: ",
repo.getName() + " (ID: " + repo.getId() + ")");
}
} else {
Log.e("Request failed: ",
"Cannot request GitHub repositories");
}
}
@Override
public void onFailure(Call<List<GitHubRepo>> call, Throwable t) {
Log.e("Error fetching repos", t.getMessage());
}
});
}
Youve got a first impression of Retrofit and know how to define an interface which represents your
API endpoints on client side. Besides that, you know how to create the API client with the help of
Retrofits Retrofit class and how to create a generic ServiceGenerator for static service creation.
https://github.com/square/retrofit/blob/master/samples/src/main/java/com/example/retrofit/SimpleService.java
Well update the ServiceGenerator in the following chapters within this book with examples for
authentication.
The next chapter shows you how to define and manipulate requests with Retrofit.
Chapter Summary
Youve mastered your first steps to become a proficient developer using Retrofit. Within this chapter,
you got an overview on Retrofit and we walked through a practice related example. You should have
learned
The next chapter is all about requests. Well guide you through the setup of Retrofit to receive and
send data with your request.
Outro
Our goal is to truly help you getting started and ultimately master Retrofit. We hope you learned
many new things throughout this book. We want you to save time while learning the basics
and details about Retrofit. The existing Retrofit documentation lacks various information and
this book should help you to gain extensive in-depth knowledge without loosing time searching
StackOverflow for correct answers.
Were currently planning new chapters and sections on Retrofit that will be added within the
upcoming months. We feel the need for an extra chapter about reactive extensions on Android
using RxAndroid/RxJava. That is the current high priority item on our idea list. Besides that, we
plan to add content on the testing chapter.
Nonetheless, well update the content of this book to later Retrofit versions as new releases become
available. However, it will take some time to update the code for breaking changes introduced to
Retrofit. Of course, well let you about any book updates.
As a reader of this book, well always reward your loyalty by publishing exclusive content and any
future update will of course be free for you!
For us its really important to exceed our readers expectations. In all our products and guides we
aim for a high quality. If you feel like a section or chapter in this book wasnt clear or extensive
enough, please let us know at [email protected]. We always love hearing back from you, so if
you have anything to say, dont hesitate to shoot us an email. We welcome any feedback, critic,
suggestions for new topics or whatever is currently on your Retrofit mind!
Dont forget, were publishing new blog posts every Monday and Thursday, mainly about Android
and Node.js within the Future Studio University. Feel free to visit our homepage and the University
:)
Thanks a lot for reading this book! We truly appreciate your interest and hope you learned a lot
from reading this book! <3
Marcus & Norman
mailto:[email protected]
https://futurestud.io
https://futurestud.io/blog