Retrofit Basics is an important topic in Android development because it simplifies how apps communicate with web servers using REST APIs. Instead of writing complex networking code, Retrofit provides a clean and structured way to send requests and receive responses.
Almost every modern Android application that works with APIs uses Retrofit for data handling.
What is Retrofit?
Retrofit is a type-safe HTTP client for Android and Java developed by Square.
It is used to:
- Send API requests
- Receive server responses
- Convert JSON into Java objects automatically
- Handle network operations easily
In simple words, Retrofit helps Android apps talk to the internet.
Why Use Retrofit?
Retrofit is important because it:
- Reduces boilerplate code
- Makes API integration easy
- Automatically parses JSON
- Supports multiple request types
- Works well with Gson
- Handles asynchronous calls
- Improves code readability
It is the most popular networking library in Android development.
How Retrofit Works
Retrofit works in three main steps:
- Define API endpoints
- Create Retrofit instance
- Make network calls
The response is usually converted into Java objects automatically using a converter like Gson.
Adding Retrofit Dependency
To use Retrofit in Android, add dependencies in Gradle:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
These libraries enable API communication and JSON parsing.
What is an API Interface?
An API interface defines all network endpoints in one place.
Example:
public interface ApiService {
}
It acts as a contract between Android app and server.
Creating GET Request
GET request is used to fetch data from server.
public interface ApiService {
@GET("users")
Call<List<User>> getUsers();
}
This endpoint returns a list of users.
Creating Retrofit Instance
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(
GsonConverterFactory.create())
.build();
ApiService apiService =
retrofit.create(ApiService.class);
This initializes Retrofit for API calls.
Making a GET Request
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();
}
}
@Override
public void onFailure(
Call<List<User>> call,
Throwable t) {
}
});
This fetches data asynchronously.
Creating POST Request
POST request is used to send data to server.
@POST("users")
Call<User> createUser(@Body User user);
This sends a new user object to the server.
Sending Data Using POST
User user =
new User("Ali", 22);
apiService.createUser(user)
.enqueue(new Callback<User>() {
@Override
public void onResponse(
Call<User> call,
Response<User> response) {
}
@Override
public void onFailure(
Call<User> call,
Throwable t) {
}
});
This sends data in JSON format automatically.
What is @GET and @POST?
@GET
Used to retrieve data from server.
Example:
@GET("products")
@POST
Used to send new data.
Example:
@POST("login")
Base URL in Retrofit
Base URL is the root address of API.
Example:
https://api.example.com/
All endpoints are added after this URL.
Example:
https://api.example.com/users
Retrofit Response Handling
Retrofit handles two main cases:
Success Response
When API call works correctly:
response.isSuccessful()
Failure Response
When request fails:
onFailure()
What is Callback?
Callback is used to handle asynchronous responses.
It contains:
- onResponse
- onFailure
This ensures the app does not freeze during network calls.
Using Model Class with Retrofit
Example model class:
public class User {
String name;
int age;
}
Retrofit automatically maps JSON into this class.
GET Request with Single Object
@GET("user/1")
Call<User> getUser();
This fetches a single user.
Passing Parameters in URL
@GET("users/{id}")
Call<User> getUserById(@Path("id") int id);
Calling method:
apiService.getUserById(5);
This fetches user with ID 5.
Query Parameters in Retrofit
@GET("users")
Call<List<User>> getUsers(@Query("page") int page);
Example request:
users?page=2
Error Handling in Retrofit
Common errors:
- No internet connection
- Server error
- Wrong URL
- Invalid JSON
Example:
@Override
public void onFailure(
Call<List<User>> call,
Throwable t) {
System.out.println(t.getMessage());
}
Logging in Retrofit
To debug API calls, use logging interceptor.
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
This helps track requests and responses.
Synchronous vs Asynchronous Calls
Synchronous
- Runs on main thread
- Not recommended
Asynchronous (Retrofit uses this)
- Runs in background
- Uses enqueue()
- Keeps app smooth
Real-World Applications
Retrofit is used in:
- Social media apps
- E-commerce platforms
- Food delivery apps
- Banking apps
- News applications
- Chat applications
- Streaming services
Almost every modern app depends on Retrofit.
Advantages of Retrofit
Retrofit provides many benefits:
- Easy API integration
- Automatic JSON parsing
- Clean code structure
- Fast development
- Supports multiple request types
- Works with Gson
- Handles errors efficiently
Limitations of Retrofit
Retrofit also has some limitations:
- Requires internet connection
- Needs backend API setup
- Debugging can be complex
- Dependency on server response structure
Common Beginner Mistakes
Wrong Base URL
Must end with โ/โ.
Not Adding Internet Permission
<uses-permission android:name="android.permission.INTERNET"/>
Not Handling Null Response
Always check:
response.body()
Running Network Calls on Main Thread
Always use enqueue().
Best Practices
When using Retrofit:
- Use clean API interfaces
- Handle errors properly
- Use model classes
- Keep base URL organized
- Add logging for debugging
- Validate API responses
These practices improve performance and maintainability.
Importance of Retrofit
Retrofit is important because it:
- Simplifies API integration
- Connects apps with servers
- Enables real-time data apps
- Reduces networking complexity
- Improves app performance
- Supports modern Android architecture
It is a core skill for Android developers.
Conclusion
Retrofit is a powerful and easy-to-use HTTP client for Android that simplifies API communication. It allows developers to send requests, receive responses, and automatically convert JSON data into Java objects. With features like GET, POST, query parameters, and asynchronous handling, Retrofit plays a key role in building modern, data-driven Android applications. Mastering Retrofit is essential for any developer working with APIs in Android.