Home  Java   Retrofit li ...

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?


2️⃣ Why use Retrofit?

  1. Type-safe API calls
  2. Automatic serialization/deserialization of JSON to Java objects
  3. Clean, declarative code using interfaces and annotations
  4. Supports asynchronous requests with callbacks or CompletableFuture
  5. Integrates easily with OkHttp for advanced features like interceptors and connection pooling

3️⃣ How Retrofit Works Internally

  1. You define a Java interface with annotations for HTTP methods (@GET, @POST, etc.)
  2. Retrofit generates an implementation at runtime using dynamic proxies
  3. Calls go through OkHttpClient (network)
  4. 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

FeatureBenefit
Annotations (@GET, @POST, @Path, @Query)Makes API calls declarative
Gson/Moshi converterAuto JSON → Java object mapping
Integration with OkHttpConnection pooling, interceptors, retries
Async supportNon-blocking API calls
Dynamic base URLsSwitch 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  
 

Comments

Add your comment