Dynamic Multiple Base URL with Annotations | Android

Mustafa Yiğit
ProAndroidDev
Published in
3 min readDec 2, 2022

--

Story

Think about having a lot of services on the backend and multiple base urls for our mobile client. How can we handle this? Overwrite the url? Absolutely no. Let’s dive too deep.

In this case, we use a different base url each environment type.

  • alpha → prefix: “alpha-”
  • beta → prefix: “beta-”
  • production → prefix: none

Also, we have multiple services.

  • auth operations → “auth.mydomain.com”
  • pay services → “pay.mydomain.com”
  • app content → “mydomain.com”

We don’t want to specify urls for each retrofit endpoint manually. So, I can use Custom Annotations to manage urls. It makes it easy.

Project Folder Structure

Here is the project folder structure.

We have three retrofit services, ApiType enum class and Api annotation class.

ApiType

We defined an enum type for each microservices. They all have a string for the hostname.

Now we need a flag to manipulate base urls for each retrofit call. We can define an annotation class and set it to each call.

EnvironmentManager & BaseUrlInterceptor

Now we know which call belongs to which service. If we catch this annotation in the interceptor, we’ll do whatever we want. Let’s do it 👇

I wrote an interceptor called BaseUrlInterceptor and a manager called EnvironmentManager which includes environments for base url operations.

Here is my EnvironmentManager. It includes predefined environments and a function for getting url by api type.

We need to catch the Api annotation from the retrofit call.

And we have an annotation and can get the base url from EnvironmentManager by apiType.

Manage Environments Dynamically

Everything is ok. But we want to control these environments dynamically. So, I created a simple selection with spinners. It will be updated environment models when the item is selected.

Firstly, we need to init spinners with our deployment types (alpha, beta, production)

We want to update the environment model when the spinner item is selected. We need to add an item select listener.

And that’s all. Let’s check it.

Now, this article ended too. I hope it will be helpful. I published a sample project with codes on Github. You can see more code details over there. If you find any trouble please write me and we will fix it. Feel free to contact me 🤙

Linkedin: @mustafayigitt

Twitter: @mustafayigitt_

--

--