19.1. Retrofit Setup
Table of Contents
Introduction
Retrofit is a popular networking library for Android that makes calling REST APIs simpler and more structured. In this chapter you will focus only on setting up Retrofit in an Android project. You will not yet design API interfaces or parse responses in detail, because those topics belong to later chapters.
The goal here is that by the end of this chapter you can add Retrofit to your project, create a basic Retrofit instance, and understand where this code belongs in an Android app.
Adding Retrofit to your project
Retrofit is added as a Gradle dependency. You always work in the app module build.gradle or build.gradle.kts file, not the project level one.
In Groovy based Gradle scripts you add dependencies inside the dependencies block.
dependencies {
implementation "com.squareup.retrofit2:retrofit:2.9.0"
}In Kotlin DSL scripts you use a slightly different syntax, but the idea is the same.
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0")
}After you add the dependency you must sync the project. Android Studio usually shows a notification at the top with a "Sync Now" button. Syncing downloads the library and makes it available to your code.
Always sync Gradle after adding or changing Retrofit dependencies. If you forget, your imports will fail and the code will not compile.
Adding a converter dependency
Retrofit only knows how to handle raw HTTP bodies by default. In real apps you almost always want Retrofit to convert JSON into Kotlin data classes automatically. This conversion is handled by a converter.
One of the most common choices is the Gson converter.
For Groovy Gradle:
dependencies {
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
}For Kotlin DSL:
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
}Later, when you configure the Retrofit instance, you will plug this converter into Retrofit so that responses can be mapped to your data classes.
Creating a basic Retrofit instance
After adding the dependencies, the next step is to create a Retrofit object. This object holds the base settings for your API calls, such as the root URL and the converter.
A minimal Retrofit instance looks like this:
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
The baseUrl must end with a /. This is a strict requirement.
Retrofit baseUrl must end with /. For example https://api.example.com/ is valid, but https://api.example.com without the trailing slash causes an error.
The converter factory connects Retrofit with Gson so JSON responses can be turned into Kotlin objects. The exact way these objects are defined is handled later in the course.
Choosing where to place the Retrofit setup
You should not create a new Retrofit instance every time you perform an API call. Creating one instance and reusing it is more efficient and easier to maintain.
A common simple pattern is to place Retrofit setup inside a Kotlin object, which gives you a singleton instance.
object RetrofitClient {
private const val BASE_URL = "https://api.example.com/"
val instance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
The by lazy keyword ensures that the Retrofit instance is created only when you use it for the first time, not when the app starts. This object can live in a file such as RetrofitClient.kt inside a network or data package.
Later, when you learn about dependency injection, you will see more advanced ways to manage this kind of global object. For now, an object is simple and works for small apps.
Adding a logging interceptor (optional but useful)
While developing and debugging, it is very helpful to see the HTTP requests and responses in Logcat. For this you use OkHttp logging interceptor. OkHttp is the HTTP client library used by Retrofit internally.
First, add the interceptor dependency.
For Groovy Gradle:
dependencies {
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.12.0"
}For Kotlin DSL:
dependencies {
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
}
Then, create an OkHttpClient with the interceptor and pass it to Retrofit.
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "https://api.example.com/"
private val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
private val httpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val instance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}You should only use detailed logging in debug builds. For release builds you normally reduce or disable logging. That build specific handling is usually done with build configs and is not the focus of this chapter.
Using the Retrofit instance to create API services
Retrofit uses interfaces to describe endpoints, which you will study in the next chapter. For setup purposes, you only need to know that you call retrofit.create(...) on your instance.
With the RetrofitClient singleton from earlier, you might later write something like this:
val retrofit = RetrofitClient.instance
val api = retrofit.create(MyApiService::class.java)
At this stage you do not have to define MyApiService. The important part is that a correctly configured Retrofit instance can now be reused across your app to create one or more service interfaces.
Summary
In this chapter you have set up Retrofit in an Android project. You added the core Retrofit library, a JSON converter, and optionally a logging interceptor. You learned how to create a single reusable Retrofit instance and where to place this setup code. In the next chapter, you will focus on defining API interfaces that use this instance to perform real network requests.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Introduction to Android Development
- ☰ 1.1. What is Android
- ☰ 1.2. Android Ecosystem and Versions
- ☰ 1.3. Native vs Cross-Platform Development
- ☰ 1.4. Course Structure and Goals
-
- ☰ 2. Setting Up the Development Environment
- ☰ 2.1. Installing Android Studio
- ☰ 2.2. Android SDK and Tools
- ☰ 2.3. Emulator Setup
- ☰ 2.4. Running Apps on a Physical Device
-
- ☰ 3. Kotlin Basics for Android
- ☰ 3.1. Variables and Data Types
- ☰ 3.2. Control Flow (if, when, loops)
- ☰ 3.3. Functions
- ☰ 3.4. Null Safety
- ☰ 3.5. Packages and Imports
-
- ☰ 4. Object-Oriented Programming in Kotlin
- ☰ 4.1. Classes and Objects
- ☰ 4.2. Constructors
- ☰ 4.3. Inheritance and Polymorphism
- ☰ 4.4. Interfaces
- ☰ 4.5. Data Classes and Enums
-
- ☰ 5. Android Project Structure
- ☰ 5.1. Android Studio Project Overview
- ☰ 5.2. Gradle Build System
- ☰ 5.3. AndroidManifest.xml
- ☰ 5.4. Resource Directories
-
- ☰ 6. Your First Android App
- ☰ 6.1. Creating a New Project
- ☰ 6.2. Understanding MainActivity
- ☰ 6.3. Running and Debugging the App
-
- ☰ 7. Android App Lifecycle
- ☰ 7.1. Activity Lifecycle
- ☰ 7.2. Lifecycle Callbacks
- ☰ 7.3. Configuration Changes
-
- ☰ 8. Layouts and Views
- ☰ 8.1. XML Layout Basics
- ☰ 8.2. LinearLayout
- ☰ 8.3. ConstraintLayout
- ☰ 8.4. View Attributes
- ☰ 8.5. Responsive Layouts
-
- ☰ 9. User Interaction
- ☰ 9.1. Buttons and Click Listeners
- ☰ 9.2. TextView and EditText
- ☰ 9.3. Handling User Input
- ☰ 9.4. Toasts and Snackbars
-
- ☰ 10. Styling and Themes
- ☰ 10.1. Colors and Dimensions
- ☰ 10.2. Styles
- ☰ 10.3. Themes
- ☰ 10.4. Dark Mode Support
-
- ☰ 11. Navigation Between Screens
- ☰ 11.1. Intents
- ☰ 11.2. Passing Data Between Activities
- ☰ 11.3. Activity Back Stack
-
- ☰ 12. Fragments
- ☰ 12.1. Fragment Basics
- ☰ 12.2. Fragment Lifecycle
- ☰ 12.3. Fragment Transactions
- ☰ 12.4. Fragment Communication
-
- ☰ 13. RecyclerView and Lists
- ☰ 13.1. RecyclerView Basics
- ☰ 13.2. Adapters and ViewHolders
- ☰ 13.3. Click Handling in Lists
-
- ☰ 14. Data Storage Basics
- ☰ 14.1. SharedPreferences
- ☰ 14.2. Internal Storage
- ☰ 14.3. File Handling
-
- ☰ 15. Databases with Room
- ☰ 15.1. SQLite Overview
- ☰ 15.2. Room Entities
- ☰ 15.3. Data Access Objects
- ☰ 15.4. Database Migrations
-
- ☰ 16. Working with Images and Media
- ☰ 16.1. ImageView and Drawable Resources
- ☰ 16.2. Loading Images from the Internet
- ☰ 16.3. Audio and Video Playback
-
- ☰ 17. Permissions and Security
- ☰ 17.1. App Permissions
- ☰ 17.2. Runtime Permissions
- ☰ 17.3. Security Best Practices
-
- ☰ 18. Networking Fundamentals
- ☰ 18.1. HTTP Basics
- ☰ 18.2. REST APIs
- ☰ 18.3. JSON Parsing
-
- ☰ 19. Networking with Retrofit
- ☰ 19.1. Retrofit Setup
- ☰ 19.2. API Interfaces
- ☰ 19.3. Error Handling
-
- ☰ 20. Background Tasks
- ☰ 20.1. Threads and Handlers
- ☰ 20.2. Kotlin Coroutines
- ☰ 20.3. Lifecycle-Aware Tasks
-
- ☰ 21. Services and WorkManager
- ☰ 21.1. Services Overview
- ☰ 21.2. Foreground vs Background Services
- ☰ 21.3. WorkManager
-
- ☰ 22. Architecture Components
- ☰ 22.1. ViewModel
- ☰ 22.2. LiveData
- ☰ 22.3. MVVM Architecture
-
- ☰ 23. Dependency Injection
- ☰ 23.1. Dependency Injection Concepts
- ☰ 23.2. Hilt Basics
-
- ☰ 24. Material Design
- ☰ 24.1. Material Design Principles
- ☰ 24.2. Material Components
- ☰ 24.3. Adaptive UI Design
-
- ☰ 25. Animations and Motion
- ☰ 25.1. View Animations
- ☰ 25.2. Property Animations
- ☰ 25.3. Transitions
-
- ☰ 26. Notifications
- ☰ 26.1. Notification Basics
- ☰ 26.2. Notification Channels
- ☰ 26.3. Action Buttons
-
- ☰ 27. Location and Sensors
- ☰ 27.1. Location Services
- ☰ 27.2. Using GPS
- ☰ 27.3. Device Sensors
-
- ☰ 28. Maps and Geolocation
- ☰ 28.1. Google Maps Integration
- ☰ 28.2. Markers and Map Events
-
- ☰ 29. Testing Android Apps
- ☰ 29.1. Unit Testing
- ☰ 29.2. UI Testing with Espresso
-
- ☰ 30. Performance Optimization
- ☰ 30.1. Memory Management
- ☰ 30.2. Profiling Tools
- ☰ 30.3. Performance Best Practices
-
- ☰ 31. App Debugging
- ☰ 31.1. Logcat
- ☰ 31.2. Breakpoints
- ☰ 31.3. Debugging Common Issues
-
- ☰ 32. App Packaging and Signing
- ☰ 32.1. APK vs AAB
- ☰ 32.2. Signing Configurations
- ☰ 32.3. Release Builds
-
- ☰ 33. Publishing on Google Play
- ☰ 33.1. Google Play Console
- ☰ 33.2. Store Listing
- ☰ 33.3. Release Tracks
-
- ☰ 34. Monetization Strategies
- ☰ 34.1. Ads
- ☰ 34.2. In-App Purchases
- ☰ 34.3. Subscriptions
-
- ☰ 35. Advanced Topics
- ☰ 35.1. Custom Views
- ☰ 35.2. Introduction to Jetpack Compose
-
- ☰ 36. Capstone Project
- ☰ 36.1. Project Planning
- ☰ 36.2. Implementation
-
Comments
Please login to add a comment.
Don't have an account? Register now!