Retrofit: Handling Dynamic URLs

Retrofit: Handling Dynamic URLs

ยท

0 min read

Before we get our hands dirty with some Retrofit, this post assumes you are already familiar with how it works to make simple requests. If you haven't, not to worry you can check this Retrofit introduction by Future Studio and come back to it.

Back to the script, recently I went back to a little project I did some months ago that involved making requests to a RESTful API, the Star Wars API to be exact. I would type a characters name and get some results from the API, but this time it didn't work but would send a 404 Not Found response ๐Ÿ˜•.

The next logical step to take was to check the URL and turns out the base URL had in fact changed/I resolved it, got it working and thought that's it problem solved. Actually no, let's have a look at the responses the API gives and see my workaround to get more context on the issue.

The Star Wars API response:

My Retrofit Service Interface:

My "Workaround":

Basically what my workaround was trying to do is extract the ids given from the links being received in the response e.g from the above response from the films JSON array it gets the id of each film and uses it to make the request. At the time of writing the code, it felt witty exercising some regex muscle and being familiar to @Path in the past also made it feel logical. However, the above solution introduces scalability and maintenance concerns, such as if the URL scheme changes when the backend team is making a couple of iterations and readability concerns.

So what do we do?

This is where Retrofits' @Url comes to shine.

Passing a value to a parameter annotated with retrofits' @Url the value will be resolved against a base URL to create the full endpoint URL. Values which have a host replace the host of the baseUrl and values also with a scheme replace the scheme of baseUrl.

E.g with one of the response values.

Has Host
Base URL: http://starwarsapi.co/
Endpoint: https://swapi.dev/api/films/2/
Result: https://swapi.dev/api/films/2/

We can now refactor our service class to use the @Url and get rid of the previous workaround and we are good to go. In the event, the API URL changes all we will care about is the base URL we used to configure the retrofit instance.

The whole project can be viewed from Github.

For more on @Url and schemes check out this comment in Retrofit.

Thanks for reading and feel free to reach out on twitter or give feedback.

Cover Photo by Alina Grubnyak on Unsplash.

Cheers.๐Ÿฅ‚