Retrofit 2 Service Generator

Though we can easily create Retrofit instances on demand for different client in place, having a dedicated factory method or service generator method is definitely desirable.

In this service generator, we can have centralized place to add/modify the authentication, logging and error handling logic.

1. Retrofit service generator

A service generator class defines one method to create a basic REST client for a given class/interface. It simply returns a service class from the provided argument interface.

In given example, we have used the API base URL to and added HttpLoggingInterceptor for logging support. Feel free to tweak the configuration.

All fields are declared as static in this class because in Android apps, we generally have one network request in progress at a time. Feel free to change it if your app require multiple connections at the same time.

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ServiceGenerator 
	private static final String BASE_URL = "";

	private static Retrofit.Builder builder = new Retrofit.Builder()

	private static Retrofit retrofit =;

	private static HttpLoggingInterceptor loggingInterceptor =
            new HttpLoggingInterceptor()

	private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

	public static <S> S createService(Class<S> serviceClass) 
		if (!httpClient.interceptors().contains(loggingInterceptor)) {
		return retrofit.create(serviceClass);

2. How to use service generator

One we have create the service generator class, all we have to do is call it’s createService() method to have a functioning REST client.

import retrofit2.Call;
import retrofit2.Response;

public class UserServiceClient 
	public static void main(String[] args) 
		UserService service = ServiceGenerator.createService(UserService.class);
		// Calling '/api/users/2'
		Call<UserApiResponse> callSync = service.getUser(2);
		    Response<UserApiResponse> response = callSync.execute();
		    UserApiResponse apiResponse = response.body();
		catch (Exception ex) 

Program output.

UserApiResponse [data=User [id=2, first_name=Janet, 

Drop me your questions in comments.

Happy Learning !!

Reference: in retrofit-oauth

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Retrofit 2 Service Generator”

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.