Sobes.tech
Junior — Middle

How to implement network API interactions in an application using the Retrofit library?

sobes.tech AI

Answer from AI

To work with network APIs in an Android application using Retrofit, you need to follow several steps:

  1. Add the Retrofit dependency in build.gradle.
  2. Create an interface describing HTTP requests using annotations (@GET, @POST, etc.).
  3. Create a Retrofit instance with a base URL and a converter (e.g., GsonConverterFactory for JSON).
  4. Create an implementation of the interface via Retrofit.
  5. Make requests asynchronously (enqueue) or synchronously (execute).

Example of interface and Retrofit creation:

interface ApiService {
    @GET("users/{id}")
    fun getUser(@Path("id") userId: String): Call<User>
}

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val api = retrofit.create(ApiService::class.java)

// Asynchronous call
api.getUser("123").enqueue(object : Callback<User> {
    override fun onResponse(call: Call<User>, response: Response<User>) {
        if (response.isSuccessful) {
            val user = response.body()
            // handle user
        }
    }

    override fun onFailure(call: Call<User>, t: Throwable) {
        // handle error
    }
})

Thus, Retrofit simplifies creating HTTP requests and parsing responses, allowing working with APIs through interfaces.