RestSharp and the factory pattern - you really should

Hackered
Sunday, April 12, 2015
by Sean McAlinden

I have been creating Web API's now for many years so creating HTTP clients in my code and acceptance tests is second nature.

One key approach I always recommend is to use the factory pattern for creating REST clients and REST request objects.

Imagine the following scenario:

You have been really diligent and covered your API's with good acceptance tests using RestSharp as your http client.

A few months into the project a story has been picked up to implement OAuth 2 client credentials security for all the endpoints.

You now need to go through all of your tests and update them to pass an Authorization header, not the most productive or interesting way to spend your day.

This is where a little encapsulation comes into its own.

The factory pattern

The factory pattern is as simple as it gets, it is essentially creating a class responsible for creating a specific instance of a type.

The following is a simple example of a class factory for creating a RestClient:

public class RestClientFactory : IRestClientFactory
{
    public RestClient Create(string baseUrl)
    {
        return new RestClient(baseUrl);
    }
}

The following is an example of a class factory for creating a RestRequest:

public class RestRequestFactory : IRestRequestFactory
{
    public RestRequest Create(string url, Method method)
    {
        return new RestRequest(url, method);
    }
}

Whilst the examples are pretty simplistic, the power comes when the request or client changes and you only have to alter them in one place and your whole code base continues to work.

The following code shows how to use the factories (I've assumed you are familiar with using dependency injection):

public class MyExampleClass
{
    private IRestClientFactory restClientFactory; 
    private IRestRequestFactory restRequestFactory;

    public MyExampleClass(IRestClientFactory restClientFactory, IRestRequestFactory restRequestFactory)
    {
        this.restClientFactory = restClientFactory;
        this.restRequestFactory = restRequestFactory;
    }

    public IRestResponse GetById(string id)
    {
        var restClient = restClientFactory.Create(configurationSettings.BaseUrl);
        var restRequest = restRequestFactory.Create(string.Format("myendpoint/{0}", id), Method.GET);
        var response = restClient.Execute(restRequest);
        return response;
    }
}

There you have it, a very simple example of encapsulation which could save you countless painful hours of refactoring.