REST API Integration in Android using Retrofit
In this tutorial, you will learn how to integrate REST APIs in Android using Retrofit. Retrofit is a powerful HTTP client for making network requests and handling JSON data easily.
What is Retrofit?
Retrofit is a type-safe HTTP client for Android that simplifies API calls and converts JSON responses into Java/Kotlin objects.
Features of Retrofit
- Easy API integration
- Supports GET, POST, PUT, DELETE
- Automatic JSON parsing
- Works with Gson, Moshi
- Supports asynchronous calls
Add Dependencies
GRADLE
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Create API Interface
Java
public interface ApiService {
@GET("posts")
Call<List<Post>> getPosts();
}
Create Model Class
Java
public class Post {
private int id;
private String title;
public int getId() { return id; }
public String getTitle() { return title; }
}
Create Retrofit Instance
Java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService api = retrofit.create(ApiService.class);
Make API Request
Java
api.getPosts().enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if(response.isSuccessful()) {
List<Post> posts = response.body();
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
t.printStackTrace();
}
});
POST Request Example
Java
@POST("posts")
Call<Post> createPost(@Body Post post);
Permissions
XML
<uses-permission android:name="android.permission.INTERNET" />
Enhancements
- Use RecyclerView to display API data
- Add loading indicators
- Handle errors properly
- Use MVVM architecture
- Use Coroutines (Kotlin)
Common Mistakes
- Missing INTERNET permission
- Wrong base URL
- Not handling null responses
- Blocking main thread
- Incorrect JSON mapping
Practice Exercises
- Display API data in RecyclerView
- Create POST request form
- Add loading spinner
- Handle API errors
- Convert project to Kotlin
Conclusion
Retrofit makes API integration simple and efficient in Android apps. Mastering it allows you to connect your app with real-world data and services.
Note: Note: Always handle network failures and edge cases for better user experience.
Codecrown