Sobes.tech
Junior — Middle

How is the Retrofit library integrated into a project?

sobes.tech AI

Answer from AI

To integrate the Retrofit library into an Android project, you need to follow several steps:

  1. Add the dependency to your app module's build.gradle file:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// To work with JSON, usually add a converter, for example Gson:
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  1. Sync your project with Gradle.

  2. Create an interface describing the HTTP requests using Retrofit annotations, for example:

public interface ApiService {
    @GET("users/{id}")
    Call<User> getUser(@Path("id") int userId);
}
  1. Create a Retrofit instance and configure it:
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ApiService apiService = retrofit.create(ApiService.class);
  1. Use apiService to perform requests and handle responses.

Thus, the integration involves adding dependencies, creating an API interface, and initializing Retrofit with the necessary parameters.