A project that makes an api call and returns data about a given zipcode entered by the user
- How to pass path to api to GET API call
- How to use @SerializedName("country abbreviation") in data classes to map attributes with spaces to proper data class variables
- Add input restrictions to TextFields to ensure only specific characters and limits are allowed
- @SerializedName annotation maps the kotlin name to the serialized name
- For example if json response has attribute of "country abbreviation" @SerializableName allows you to access that attribute with a custom name you want to use in your code "countryAbbreviation"
- This is usally benefitial after using Json to Kotlin plugin which converts json to data classes and some times data class attribute names generated by this plugin are not valid kotlin variable names
Example
data class ZipDataModel(
@SerializedName("country abbreviation") // -> plugin generates variable name with space
val countryAbbreviation: String? = "", // -> you can map json attribute name to a valid kotlin variable name
)
When passing path variable when calling api make sure it is called in this way
ApiDetails.kt
object ApiDetails {
// API -> https://api.zippopotam.us/us/33162
// endpoint and base url
const val BASE_URL = "https://api.zippopotam.us/"
const val ENDPOINT_ZIP_DATA = "us"
const val ZIP_PATH = "/{zipCode}"
}
ZipDataApi.kt
interface ZipDataApi {
@GET(ApiDetails.ENDPOINT_ZIP_DATA + ApiDetails.ZIP_PATH)
suspend fun getZipDataBYZip(@Path ("zipCode") zipCode:Int): ZipDataModel
}
ZipDataRepository.kt
class ZipDataRepository @Inject constructor(
private val api: ZipDataApi
){
suspend fun getZipDataByZip(zipCode:Int) = api.getZipDataBYZip(zipCode)
}