Skip to content

mkCoding/ZipCodeData

Repository files navigation

Description

A project that makes an api call and returns data about a given zipcode entered by the user

What I Learned

  • 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

Important Notes 1

  • @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

)

Important Notes 2

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)
}

Video Proof

Zip.Code.Report.Proof.mov

About

Application where I make api call to retrive info about a given zipcode entered by the user

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages