CPS251 Android Development by Scott Shaper

Building the WeatherApiService

The WeatherApiService file describes the weather endpoint we call with Retrofit. This interface is a contract: it tells Retrofit what URL path to use, what query parameters to send, and what Kotlin type should be returned.

interface WeatherApiService {
    @GET("data/2.5/weather")
    suspend fun getCurrentWeather(
        @Query("zip") zip: String,
        @Query("appid") appId: String,
        @Query("units") units: String = "metric"
    ): WeatherResponse
}

Code Explanation

Interface as an API Contract

Endpoint Annotation

Suspend Function

Query Parameters

Return Type

How It Connects to the App

Learning Aids

Tips for Success

  • Think of each function in this interface as one API endpoint.
  • Use clear parameter names that match what the API expects.
  • Keep endpoint functions suspend when they perform network I/O.
  • Use default parameter values when the API has a common default behavior.
  • Keep this file focused on endpoint definitions only.

Common Mistakes to Avoid

  • Misspelling query names like appid or zip.
  • Forgetting suspend and then calling network code on the wrong thread.
  • Using the wrong endpoint path in @GET.
  • Returning the wrong data class type that does not match the JSON structure.
  • Mixing business logic into this interface.

Best Practices

  • Keep API interfaces clean and declarative.
  • Use one service interface per feature area when possible.
  • Return strongly typed models (like WeatherResponse) for safety and readability.
  • Use repository classes to wrap service calls and handle errors.
  • Document required query parameters in comments or lesson text for teammates.