Sobes.tech
Junior — Middle

How can you configure an API call through Retrofit to specify a function for executing a particular request?

sobes.tech AI

Answer from AI

To set up API calls via Retrofit, you need to:

  1. Create an interface with methods annotated with HTTP methods (@GET, @POST, etc.).
  2. Specify the path and request parameters in the methods.
  3. Create a Retrofit instance and implement the interface.

Example:

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

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

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

// Calling the function for a specific request
val call = api.getUser("123")
call.enqueue(object : Callback<User> {
    override fun onResponse(call: Call<User>, response: Response<User>) {
        // handle response
    }

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

Thus, the specific request is made by calling the corresponding method of the interface.