
Introduction
Retrofit is one of the most popular HTTP libraries for Android. It is developed by Square and is used to connect Android applications with REST APIs.
Using Retrofit, you can easily:
Fetch data from APIs
Send data to servers
Upload files
Handle JSON responses
Integrate RESTful services
In this tutorial, you will learn how to integrate Retrofit API in Android using Java.
What is Retrofit?
Retrofit is a type-safe HTTP client for Android.
Without Retrofit:
HttpURLConnection
With Retrofit:
Call<User> call = api.getUser();
Much cleaner and easier.
Prerequisites
Before starting:
Android Studio
Java Knowledge
Internet Connection
Android Project
Step 1: Add Internet Permission
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Step 2: Add Retrofit Dependency
app/build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Sync Project.
API Example
We'll use:
https://jsonplaceholder.typicode.com/users
This is a free testing API.
Step 3: Create Model Class
User.java
public class User {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
Step 4: Create API Interface
ApiService.java
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiService {
@GET("users")
Call<List<User>> getUsers();
}
Understanding Annotations
GET Request
@GET("users")
Fetch data from:
/users
POST Request
@POST("users")
Send data.
PUT Request
@PUT("users/{id}")
Update data.
DELETE Request
@DELETE("users/{id}")
Delete data.
Step 5: Create Retrofit Client
RetrofitClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static final String BASE_URL =
"https://jsonplaceholder.typicode.com/";
private static Retrofit retrofit;
public static Retrofit getClient() {
if(retrofit == null) {
retrofit =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(
GsonConverterFactory.create()
)
.build();
}
return retrofit;
}
}
Step 6: Create Layout
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnLoad"
android:text="Load Users"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Step 7: Fetch API Data
MainActivity.java
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity
extends AppCompatActivity {
Button btnLoad;
@Override
protected void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoad =
findViewById(R.id.btnLoad);
btnLoad.setOnClickListener(v -> {
loadUsers();
});
}
private void loadUsers() {
ApiService apiService =
RetrofitClient
.getClient()
.create(ApiService.class);
Call<List<User>> call =
apiService.getUsers();
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(
Call<List<User>> call,
Response<List<User>> response) {
if(response.isSuccessful()) {
List<User> users =
response.body();
for(User user : users) {
Log.d(
"USER",
user.getName()
);
}
}
}
@Override
public void onFailure(
Call<List<User>> call,
Throwable t) {
Log.d(
"ERROR",
t.getMessage()
);
}
});
}
}
How enqueue() Works
call.enqueue(...)
Runs API request asynchronously.
Benefits:
No UI freeze
Fast response
Background thread execution
GET Request Example
@GET("users")
Call<List<User>> getUsers();
Used to fetch data.
POST Request Example
Create User:
@POST("users")
Call<User> createUser(
@Body User user
);
Sending Data
User user =
new User(
"Anoj",
"anoj@gmail.com"
);
api.createUser(user);
Path Parameter Example
API:
/users/1
Interface:
@GET("users/{id}")
Call<User> getUser(
@Path("id") int id
);
Usage:
api.getUser(1);
Query Parameter Example
API:
/users?id=1
Interface:
@GET("users")
Call<List<User>> getUser(
@Query("id") int id
);
Response Handling
Success:
response.isSuccessful()
Status Code:
response.code()
Response Body:
response.body()
Error Body:
response.errorBody()
JSON Example
API Response:
[
{
"id": 1,
"name": "Leanne Graham",
"email": "leanne@gmail.com"
}
]
Converted Automatically:
List<User>
using Gson.
Common Errors
Base URL Missing Slash
Wrong:
https://jsonplaceholder.typicode.com
Correct:
https://jsonplaceholder.typicode.com/
Internet Permission Missing
Error:
Unable to resolve host
Solution:
Add INTERNET permission.
Null Response
Cause:
response.body()
is null.
Solution:
Check:
response.isSuccessful()
first.
Best Practices
✅ Create separate RetrofitClient
✅ Use Model Classes
✅ Use Repository Pattern
✅ Handle API Errors
✅ Show ProgressBar
✅ Use RecyclerView for Data Display
Retrofit Architecture
API
↓
Retrofit
↓
Model Class
↓
Repository
↓
ViewModel
↓
UI
Used in modern Android apps.
Why Developers Prefer Retrofit?
Easy to use
Fast
Clean code
Automatic JSON parsing
Supports GET, POST, PUT, DELETE
Works perfectly with Firebase and MVVM
Conclusion
Congratulations! 🎉
You have successfully integrated Retrofit API in Android using Java.
You learned:
Retrofit Setup
GET Requests
POST Requests
Query Parameters
Path Parameters
JSON Parsing
Error Handling
Retrofit is one of the most important libraries every Android developer should learn because almost every modern app communicates with APIs.
Next Tutorial
RecyclerView in Android (Java)
MVVM Architecture in Android
Room Database CRUD
Firebase Authentication
Firebase Realtime Database
Enjoyed this tutorial?
Consider supporting Pal Coder so we can keep creating high-quality, free Android development resources.