In this tutorial, we'll learn how to make REST API calls in Android using Retrofit, a powerful HTTP client library.
Setting Up Retrofit
First, we need to add Retrofit to our project dependencies. Add the following lines to your `build.gradle` file:
gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // For JSON serialization/deserialization
Creating Retrofit Interface and Model Class
Retrofit Interface :
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface ApiService {
@GET("posts/{id}")
Call<Post> getPost(@Path("id") int postId);
}
Model Class
public class Post {
private int userId;
private int id;
private String title;
private String text;
// Getters and setters
}
Making API Calls
We create a Retrofit instance, make API calls, and handle the response in our Android activity:
Create Retrofit Instance
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Make API Calls
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApiService apiService = RetrofitClient.getRetrofitInstance().create(ApiService.class);
Call<Post> call = apiService.getPost(1); // Example call for getting post with ID 1
call.enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()) {
Post post = response.body();
// Do something with the post object
Log.d("API_RESPONSE", "Title: " + post.getTitle());
} else {
Log.e("API_ERROR", "Failed to fetch post");
}
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
Log.e("API_FAILURE", "Error: " + t.getMessage());
}
});
}
}
Conclusion
In this tutorial, we've covered the basics of making REST API calls in Android using Retrofit. Retrofit simplifies the process of interacting with RESTful APIs and is widely used in Android development.
Happy coding!
0 Comments