URL builder

To get data from a REST service does not require a lot of work. A developer needs to create a query and pass the query string to an instance of HttpClient.

Fair enough. But lack of the logic, which manages how URLs are built, eventually will lead to code spaghetti with zillions of String.Format expressions and duplications.

Even more, at some point you might need to switch an app to a test environment. It means, that your code should create a query taking in account some app settings.

To get rid of the outlined complexity can help Builder pattern.

Any url to a REST api service has similar structure:

https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2

or

scheme://host/api version/relative path?query parameters

If we would like to build a client for Twitter, we would use scheme+host+version in every query. That’s a common part. URL builder is responsible to compose the common part with relative path and adds parameters to the resulting string.

Using Builder pattern, implies initializing an object without parameters or with few of them. The construction of the object is done during runtime. In my case, UrlBuilder has a constructor, which accepts a host string and a version.

Relative path and parameters can be added later depending on the context:

An example of usage:

It’s useful to wrap up an UrlBuilder initialization. A factory is a good way to do it. Let’s back to an example for Twitter API.

We can have a parent class to keep base logic:

And another factory for statuses services:

The example contains two methods. But of course, the factory can be extended depending on your needs. Personally, I create a factory per services group. For Twitter API, I would add a factory for statuses, friendships and etc.

That’s it about UrlBuilder.

Fruitful coding!


Leave a Reply