Junior — Middle
Explain the main components and principles of Retrofit for interacting with REST API.
sobes.tech AI
Answer from AI
Retrofit is a library for Android that simplifies working with REST APIs. It allows you to describe HTTP requests as interfaces, and then automatically converts responses into Java/Kotlin objects.
Main components:
- API Interface — describes methods with annotations (@GET, @POST, etc.), indicating the request type and path.
- Converter — converts JSON or other response formats into objects (e.g., GsonConverter).
- Call — an object representing a request that can be executed synchronously or asynchronously.
Working principle:
- Create an interface with methods and annotations.
- Create a Retrofit instance with a base URL and converter.
- Obtain an implementation of the interface via Retrofit.
- Call methods to get a Call and execute the request.
Example:
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 service = retrofit.create(ApiService::class.java)
val call = service.getUser("123")
call.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
}
})