CPS251 Android Development by Scott Shaper

Building the RetrofitClient

The RetrofitClient file creates and configures Retrofit for the whole app. Think of it as the "network setup station" where we tell the app which website to call and how to turn JSON into Kotlin objects.

object RetrofitClient {
    private const val BASE_URL = "https://api.openweathermap.org/"

    val weatherApiService: WeatherApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(WeatherApiService::class.java)
    }
}

Code Explanation

Why Use an Object?

Base URL

Lazy Initialization

Retrofit Builder Chain

How This Fits the Architecture

Learning Aids

Tips for Success

  • Keep your Retrofit setup in one file so it is easy to maintain.
  • Use a singleton (object) for network clients in small to medium apps.
  • Always include the trailing slash in the base URL when using Retrofit.
  • Use a converter factory (like Gson) when the API returns JSON.
  • Use by lazy when an object can be created on first use.

Common Mistakes to Avoid

  • Forgetting the trailing slash in BASE_URL which can break endpoint building.
  • Creating a new Retrofit instance in multiple files instead of sharing one setup.
  • Not adding a converter factory, then wondering why JSON parsing fails.
  • Putting endpoint paths in this file instead of the API service interface.
  • Mixing UI logic into network setup files.

Best Practices

  • Keep this file focused on configuration only.
  • Expose typed services (like WeatherApiService) instead of exposing raw Retrofit everywhere.
  • Use clear naming so new developers can quickly find networking setup.
  • In production apps, add logging interceptors and timeout configuration as needed.
  • Test your API service methods with known inputs before wiring into complex UI flows.