Retrofit library example in Java
Retrofit is a very common library in Java/Android for REST API calls, and understanding it deeply is a great interview topic. Let’s break it down step by step.
1️⃣ What is Retrofit?
- Retrofit is a type-safe HTTP client for Java and Android developed by Square.
- It converts HTTP APIs into Java interfaces.
- Supports synchronous and asynchronous requests, JSON parsing, and easy integration with libraries like Gson or Moshi.
- Works on top of OkHttp, so it benefits from connection pooling, retries, and HTTP/2.
2️⃣ Why use Retrofit?
- Type-safe API calls
- Automatic serialization/deserialization of JSON to Java objects
- Clean, declarative code using interfaces and annotations
- Supports asynchronous requests with callbacks or
CompletableFuture - Integrates easily with OkHttp for advanced features like interceptors and connection pooling
3️⃣ How Retrofit Works Internally
- You define a Java interface with annotations for HTTP methods (
@GET,@POST, etc.) - Retrofit generates an implementation at runtime using dynamic proxies
- Calls go through OkHttpClient (network)
- Response JSON is automatically converted to Java objects using a converter (e.g., GsonConverterFactory)
4️⃣ Retrofit Example
Step 1: Add dependencies
<!-- Maven -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.9.0</version>
</dependency>
Step 2: Define the API interface
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import java.util.List;
interface ApiService {
@GET("posts")
Call<List<Post>> getPosts();
@GET("posts/{id}")
Call<Post> getPostById(@Path("id") int id);
}
Step 3: Create a model class
class Post {
private int userId;
private int id;
private String title;
private String body;
// getters and setters
}
Step 4: Build Retrofit instance
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Step 5: Make API calls
Synchronous call
Call<Post> call = apiService.getPostById(1);
Post post = call.execute().body(); // blocks thread
System.out.println(post.getTitle());
Asynchronous call
apiService.getPosts().enqueue(new retrofit2.Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, retrofit2.Response<List<Post>> response) {
if(response.isSuccessful()) {
response.body().forEach(p -> System.out.println(p.getTitle()));
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
t.printStackTrace();
}
});
5️⃣ Features & Advantages
| Feature | Benefit |
|---|---|
| Annotations (@GET, @POST, @Path, @Query) | Makes API calls declarative |
| Gson/Moshi converter | Auto JSON → Java object mapping |
| Integration with OkHttp | Connection pooling, interceptors, retries |
| Async support | Non-blocking API calls |
| Dynamic base URLs | Switch between dev/staging/prod easily |
6️⃣ Interview Answer
“Retrofit is a type-safe HTTP client for Java/Android. You define REST APIs as interfaces with annotations, and Retrofit generates the implementation at runtime. It handles network calls using OkHttp and automatically converts JSON responses into Java objects using converters like Gson. It supports both synchronous and asynchronous requests, making API integration cleaner and more reliable.”
Published on: Oct 05, 2025, 11:49 PM