Retrofit: Love Working with APIs on Android
Retrofit: Love Working with APIs on Android
Take delight in building API clients on Android.
About the Book
Painless Networking with Retrofit
The content of this book is completely updated to Retrofit 2.5!
Every modern Android app needs to connect to at least one private or public API. Interacting with services can be difficult due to the extreme variety of request and response formats. Depending on the API, you’ll need to change your request payloads, authentication, data formats, and much more.
Retrofit: a type-safe HTTP client for Android and Java
Retrofit handles all of the complicated and repetitive parts of network implementations for you. It hides the entire network layer, from creating a connection to processing the handling on a separate thread, from you. Retrofit even does the mapping of the requests and responses to Java objects for you (e.g., creating a JSON payload from your passed List<User>
). You only need to describe what and how you want to send or receive it.
This awesomeness comes at a cost: an initial learning curve. Retrofit might look a little more complicated at the beginning, but pays off multiple times in the long run.
If you’re thinking about using Retrofit, or haven’t developed a deep knowledge of it yet, you’ll benefit from this book. We’ve created this book with the vision of being the ultimate guide to understanding Retrofit. After working through this book, you’ll be able to connect to new APIs and services within minutes.
You can find a Retrofit tutorial series on our website and our free video tutorial series on YouTube, where we describe some elements of Retrofit. The book extends and connects these tutorials into one common thread that guides you through all important aspects of Retrofit. The chapters are structured in a way that rewards a linear reading. Retrofit rookies can and should read it cover to cover. Experienced Retrofit developers can jump to specific sections for guides on how to solve their specific problem.
What Topics Are Covered in This Book?
The list below provides a comprehensive overview of covered topics in the book.
- Introduction to Retrofit
- Quick Start Guide to jump right into Retrofit
- Creating a sustainable Android REST client
- Extensive manipulation and customization of requests (e.g., query and path parameters, form-urlencoding, synchronous vs. asynchronous)
- Cancel, analyze and re-use requests
- Comprehensive overview of response converters and data mapping with plenty practical examples of applied (custom) converters
- Implementing and handling authentication (basic, token, OAuth, hawk) in a smart way
- File uploads, including multiple and dynamic amounts of files (optionally with progress updates)
- File download (optionally with progress updates)
- Detailed chapter on implementing pagination
- Introduction and example of possible ways to deal with errors in a clean way
- Debug requests and responses using three logging tools (OkHttp, Stetho, Android Studio Profiler)
- Fundamentals for mocking server responses
- Entire chapter on practical examples of custom converters dealing with specific scenarios
- Detailed introduction to call adapters, including custom implementations
- Extensive chapter on implementing response caching with Retrofit
- Example for an offline mode based on cached server responses
- A chapter with practical tips & tricks (including crawling websites with Retrofit)
- App release preparation including ProGuard configuration
Additionally to the regular content we provide an appendix with three sections:
- Upgrade guide from Retrofit 1.9 to 2.0
- Java basics for Retrofit
- Network basics for developers, who just started interacting with APIs
Who Is This Book For?
In short: this book is for you. We believe that every developer reading this book will take away new ideas on how to optimize their Android apps in the sense of interacting with APIs or web services using Retrofit. You’ll recognize goodies that are applicable for the projects you’re working on.
This book is for Android developers, who want to receive a substantial overview and reference book on Retrofit. You’ll benefit from clearly recognizable code examples related to your daily work with Retrofit.
Rookie
If you’re just starting out with Retrofit (or coming from another HTTP library like Android Asynchronous Http Client or 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 you’ve already worked with Retrofit, you’ll 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 uploads and downloads, and much more!
One focus of this book is not only to implement the requirements, but also do so in a clean way. We’ve seen way to many complicated and messy usages of Retrofit. We focus on providing code samples which adhere to clean code standards. We avoid any unnecessary duplication at all costs. This has the side effect of some extra app performance gains by efficient Java object handling.
Source Code Samples
With the purchase of this book, you benefit from the sample project that awaits your download within the extras section on Leanpub. The sample project is an Android project based on gradle. You can directly touch and use classes that are only illustrated in excerpts within this book.
Check your Leanpub Library and select Retrofit: Love working with APIs on Android to download the sample code base.
Continuous Updates
We’ve published the first version of this Retrofit book in July 2015. Since this initial release we’ve extended and updated the book more than a dozen times. Once you buy the book, you get all future updates for free. Even if it’s a huge Retrofit update, for example from version 1.9 to 2.0. With every new release of Retrofit we’ll evaluate the entire book content and update it accordingly.
Of course, we’re listening to your feedback and add new sections and even chapters, if it can be useful to all readers. If you still have a question after reading this book, let us know and we might be able to help!
Still Unsure?
If you’re still on the fence if this book helps you, checkout the sample or, even better, use Leanpub’s (and our) happiness guarantee. Try this book out and if you don’t think this book provides enough value, you can refund your money within 45 days with no questions asked. You don’t have any risk in testing this book, which saves you hours of headaches and makes your Android app code so much cleaner.
Final Note: Retrofit Book for Version 1.9
The current version of this book is fully focused on Retrofit 2.x, no hint or code snippet that points to Retrofit 1. If you’re interested in the first version of the book that based on Retrofit 1, please visit this book’s extras page on Leanpub. As a reader of this book, the first version is also available for you!
Bundles that include this book
About the Contributors
Norman is passionate Android developer since 2011. He's developed multiple apps, which have been used by millions of users overall. Building high-quality products is always Norman's #1 focus. While working as an Android freelancer and consultant is his day job, he loves teaching and passing on knowledge on the side.
Since 2014, Norman started working on the API side as well. Developing node.js apps is a good alternative and provides some good insight into becoming a better programmer overall.
Norman has a Master's degree from the Otto von Guericke University Magdeburg.
Table of Contents
-
Introduction
- What Topics Are Waiting for You?
- Who Is This Book For?
- The Source Code
- Retrofit Book for Version 1.9
-
Chapter 1 — Quick Start & Create a Sustainable REST Client
- Retrofit Overview
- Why Use Retrofit?
- Retrofit vs. OkHttp
- Quick Start: Add Retrofit to Your Project
- Sustainable Android REST Client
-
The
ServiceGenerator
- Retrofit in Use
-
Chapter 2 — Requests
- Retrofit API Declaration
- Url Handling, Resolution and Parsing
- Query Parameter
- Path Parameter
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Constant, Default and Logic Values for POST and PUT Requests
- Send Data Form-Urlencoded
- Add Request Header
- Reuse, Analyze & Cancel Requests
- Customize Network Timeouts
- Ignore Response Payload with Call<Void>
-
Chapter 3 — Data Mapping with Retrofit Converters
- Integrate a JSON Converter
- Integrate an XML Converter
- Integrate Other Standard Formats
- Deal with Multiple Converters
- Integrate Your Own Custom Converter
- Access Mapped Objects and Raw Response Payload
- Further Custom Converter Examples
-
Chapter 4 — Authentication
- Authentication Interceptor
- Basic Authentication
- Token Authentication
- OAuth 2
- OAuth — Refresh Your Access Token
- Hawk Authentication
- Dynamic Endpoint-Dependent Interceptor Actions
-
Chapter 5 — File Upload & Download
- File Upload
- Upload of Multiple Files
- Upload of Dynamic Amount of Files
- Uploading Files with Progress Updates
- Passing Multiple Parts Along a File with @PartMap
- File Download
- File Download with Progress Updates
-
Chapter 6 — Pagination on Android
- Pagination Response Status
- Pagination Using Query Parameter
- Pagination Using Link Header and Dynamic Urls (Like GitHub)
- Pagination Using Range Header Fields (Like Heroku)
-
Chapter 7 — Error Handling
- Error Handling Preparations
- Simple Error Handler
- Error Handling for Synchronous Requests
- How to Detect Network and Conversion Errors in onFailure
- Catch Server Errors Globally with Response Interceptor
-
Chapter 8 — Logging
- Log Requests and Responses with Retrofit
- Enable Logging for Debug Builds Only
- Log Network Traffic with Stetho and Chrome Developer Tools
- Analyze Network Traffic with Android Studio Profiler
-
Chapter 9 — Multiple Server Environments
- Product-Flavor-Dependent Base URLs
- Change API Base URL at Runtime
-
Chapter 10 — Caching
- Activate Response Caching (Etag, Last-Modified)
- Check Response Origin (Network, Cache, or Both)
- Analyze Cache Files
- Force Server Cache Support with Response Interceptor
- Support App Offline Mode by Accessing Response Caches
-
Chapter 11 — Client-Side Mocking of Server Responses
- Why Mocking Responses Make Sense
- Create Your Own MockRetrofit Implementation
- Customizing Network Behavior of Mocked Server Responses
-
Chapter 12 — Practical Converters
- Handling of Empty Server Responses
- Supporting JSON and XML Responses Concurrently
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses
- Wrapping Requests in Envelope
-
Chapter 13 — Call Adapters
- Call Adapter Basics — What Are They?
- Integration of Retrofit Callbacks into Your RxJava 1 Flow
- Integration of Retrofit Callbacks into Your RxJava 2 Flow
- Integration of Retrofit Callbacks into Your Guava Flow
-
Separating
onResponse
Callback with Custom Call Adapter -
Separating
onFailure
Callback with Custom Call Adapter
-
Chapter 14 — Practical Usages
- Share OkHttp Client and Converters between Retrofit Instances
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Receive Plain-String Responses
- Crawl HTML Responses with jspoon (Wikipedia Example)
-
Chapter 15 — App Release Preparation
- Enable ProGuard
- Configure ProGuard Rules for Retrofit
- Obfuscated Stack Traces
-
Appendix A — Retrofit 2 Upgrade Guide from 1.x
- Introduction
- Maven & Gradle Dependencies
- RestAdapter —> Retrofit
- setEndpoint —> baseUrl
- Base Url Handling
- Dynamic Urls
- OkHttp Required
- Interceptors Powered by OkHttp
- Synchronous & Asynchronous Requests
- Cancel Requests
- No Default Converter
- RxJava Integration
- No Logging
- Future Update: WebSockets in Retrofit 2.2
- Conclusion
-
Appendix B — Java Basics for Retrofit
- Java Annotations
- Java Callbacks
- Fluent Interface with Builders
-
Appendix C — Network Basics for Retrofit
- HTTP Basics
- Client Requests
- Request Methods
- Server Responses
- Status Codes
- Future Protocols
- Outro
-
Future Studio Books
- Gson
- Glide
- Picasso
- Future Studio Bundle
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earned$12,046,757writing, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
Talking with Tech Leads
Patrick KuaA book for Tech Leads, from Tech Leads. Discover how more than 35 Tech Leads find the delicate balance between the technical and non-technical worlds. Discover the challenges a Tech Lead faces and how to overcome them. You may be surprised by the lessons they have to share.Functional Event-Driven Architecture
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way. Learn to design and develop distributed systems that scale. Identify common design patterns in such systems.
Take your functional programming skills to the next level by joining me in developing a distributed system powered by Apache Pulsar and Fs2 streams, all in Scala 3!
Machine Learning Q and AI
Sebastian Raschka, PhDHave you recently completed a machine learning or deep learning course and wondered what to learn next? With 30 questions and answers on key concepts in machine learning and AI, this book provides bite-sized bits of knowledge for your journey to becoming a machine learning expert.
Getting to Know IntelliJ IDEA
Trisha Gee and Helen ScottIf we treat our IDE as a text editor, we are doing ourselves a disservice. Using a combination of tutorials and a questions-and-answers approach, Getting to Know IntelliJ IDEA will help you find ways to use IntelliJ IDEA that enable you to work comfortably and productively as a professional developer.
The Rails 7 Way
Obie Fernandez, Lucas Dohmen, and Tom Henrik AadlandThe Rails™ 7 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. It illuminates the entire Rails 7 API, its most powerful idioms, design approaches, and libraries. Building on the previous editions, this edition has been heavily refactored and updated.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #5
1500 QUIZ COMMENTATI (3 libri)
3 Books
Tre libri dei QUIZ MMG Commentati al prezzo di DUE! I QUIZ dei concorsi ufficiali di Medicina Generale relativi agli anni: 2000-2001-2003-2012-2013-2014-2015-2016-2017-2018-2019-2020-2021 +100 inediti Raccolti in unico bundle per aiutarvi nello studio e nella preparazione al concorso. All'interno di ogni libro i quiz sono stati suddivisi per... - #6
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #8
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity... - #9
Development and Deployment of Multiplayer Online Games, Part ARCH. Architecture (Vol. I-III)
3 Books
What's the Big Idea? The idea behind this book is to summarize the body of knowledge that already exists on multiplayer games but is not available in one single place.And quite a fewof the issues discussed within this series (planned as three nine volumes ~300 pages each), while known in the industry, have not been published at all (except for...