Probably giving up my CSharp Github API

I’ve been thinking that I’m going to retire my CSharp Github API. The ugly truth is that I’ve barely worked on it, literally in months. I did a little bit recently, and I had one or two good ideas about certain things, but, I do have to be honest with myself. I am not not admitting defeat, I know that I am capable enough to finish it.

I’m simply bored with it.

Also, someone has already beaten me to it, and is writing something that is actually far superior to what I’d managed to push out. In my defence, I haven’t done very much anyway, so anything that is fairly substantial is going to look better by default.

So, I’m going to knock it on the head. I’ll leave the code, such as it is, up on Github.

Stupid design decisions with the Github API wrapper

Whilst writing some blog posts about the authentication which I’ve been implementing, I’ve come to the realization, almost as an after thought, that even though I’ve still not got a lot of the main Github API implemented, the way I’ve envisioned the API working, from a user point of view, is sort of a bit shit.

var userApi = new UserApi();
var user = userApi.GetUser("example");

Pretty straightforward, right? What about the as yet unwritten GistApi?

var gistApi = new GistApi();
var gist = gistApi.GetGist(...);

Again, pretty straightforward. But I see a pattern forming. What am I going to do when it comes to the RepositoryApi?

var reposApi = new RepositoryApi();
var repo = reposApi.GetRepository(...);

Well, that is starting to look pretty fucking stupid. I’ve caught myself doing it with other methods as well. I simply cannot believe I’ve let myself be so stupid. At least there is not that much implemented where I’ll have to refactor loads of shit.

Adding authentication on the fly to a RestSharp client request

The Basics

The typical way that you’d make a request with RestSharp:

  1. Create a RestRequest
  2. Create a RestClient
  3. Execute the request with the client
  4. Do something with the response.

It’s at the point that you get the client object that you may wish to add authentication. For example with a REST API such as Githubs, certain methods behave differently if the request is authenticated or not, so being able to magically turn on authentication is desirable.

To authenticate a request with RestSharp, it is a simple case of creating a RestRequest, RestClient and an IAuthenticator instance for the authenticating mechanism you want to use. For example:

var client = new RestClient
             {
                 BaseUrl ="https://api.github.com",
                 Authenticator = new HttpBasicAuthenticator(username, password)
             };

This is pretty straightforward and standard RestSharp usage. You may have a class to encapsulate this functionality, with a method which returns the RestClient instance, probably in a base class in order to inherit this common functionality in other classes.

public abstract class BaseApi
{
    RestClient GetRestClient()
    {
        ...
    }
}

Options

There are several methods which we can use to add authentication dynamically to the RestClient instance, ranging from the trivial to the more involved.

The trivial solution is to add the IAuthenticator as a parameter to the method, which is then assigned to the RestClient when it is created. Easy. Also fairly easy is just make it abstract or virtual and override it in an inheriting class, although this breaks SRP.

Alternatively, we can implement the Decorator pattern, and introduce the authentication in a class which is solely responsible for handing it. I’m not going to go into this in too much detail, there is a wealth of information on implementing this pattern already available on the web. Using a Decorator is valid in a lot of situations, particularly when re-factoring someone else’s mess, as you can adhere to the same interface and not risk breaking some important business function. In other cases, it is better to intercept.

Interception

A pattern which lends itself to this is called Proxy, and if you spend any time with Google and search terms like “c# proxy pattern” you’ll quickly end up finding a lot of information about implementing it. You’ll also find interesting stuff about Castle.DynamicProxy, and you may quickly realise this is an excellent way of adding the ability to dynamically intercept a method to add additional functionality on the fly. I’ve implemented an interceptor in the Github API library, with the core magic being:

public void Intercept(IInvocation invocation)
{
    invocation.Proceed(); // let the RestClient be instantiated as normal.
    var restClient = (RestClient)invocation.ReturnValue;
    restClient.Authenticator = _authenticator; // add the authenticator
    invocation.ReturnValue = restClient;
 }

I then wrap the interception up in a static class, which is a technique I saw on another website, which I then wrap in a extension method which with a little bit of generics hangs off API classes in a fluent manner.

var api = new UserApi(GitHubUrl).WithAuthentication(authenticator);

I feel like it is the best way to do this sort of thing, and I will certainly starting using more of it, where necessary, in all my projects.

Github API: Handling authentication

With v3 of the Github REST API, calling a certain methods when unauthenticated will return a limited set of information, and when authenticated will return extra information. One of the things I wanted to do was to make it easy, in a fluent manner, to add authentication to a request. For example:

var a = new UserApi();
var user = a.WithAuthentication(authenticationObject).GetUser("example");
var b = new UserApi().WithAuthentication(authenticationObject);
user = b.GetUser("example");

Thus making it possible to instantiate an API object without having to authenticate, then when authorization for an action is required, the authentication can be provided. When that actually happens is, I think , something that is an implementation detail best left to future consumers of the library. Assuming I get it finished.

I got bogged down over the course of several months in trying to wrap my head around a clean way of implementing this. Initially I had a good inheritance from an Api base class to the UserApi class – this is sensible, the base Api class does after all contain methods which are going to be common to different classes, such as GistsApi, RepositoriesApi etc.

Then things got a little screwy.

At that point I had the following implemented:

var github = new Github(authenticator);
var user = gitHub.User.GetUser("example");
user.Authenticated.AddEmail("example@example.com");

Which doesn’t seem all that bad. The User property on the Github object was an instance of UserApi. When the example User is fetched, the UserApi object was added an internal instance on the User object. Then the Authenticated property on the User object returned a new AuthenticatedUser, which acted as a wrapper to the internal UserApi instance where the actual AddEmail was hidden as internal.

Needless to say, I knew something was wrong with that, and I spent far too long in coming up with a more elegant solution.

In my second stab at things, I tried to implement Decorator to solve this problem, that is, decorate the UserApi with the additional functionality to add the authentication. The trouble is that the way I wanted to implement the pattern wouldn’t have lent itself exceedingly well to having specific functionality for the different parts of the api.

Then I thought to myself, wouldn’t it be great if I could intercept the method in the base class which gets the RestClient and add the authentication to it on the fly. A little Googling taught me that this is idealised as the Proxy pattern, from which it was but a short leap to the Castle project and DynamicProxy.

 

Is this thing on?

Despite many months of not posting anything on this blog (OK, nearly a year) I am returning with another post about my on/off project to write a C# library to access the Github REST API. Much like my blogging schedule, which can arguably be said to be none-existent, my pet-project’s suffer from the same cruel lack of… habit.

To recap this particular project, you may like to browse some of the earlier posts on it, wherein I grandly proclaim my intent to write a “Github API in C#”. Which I should really have finished by now. As you will have no doubt realised, I do suffer from a certain amount of laziness. That is a subject for another blog post. To my shame, I can tell you that the amount of Github’s REST API which I’m covering is minimal, limited to a subset of the available User related commands.

Moving swiftly along, with no trace of irony.

In the months since the start of this project, Github has release v3 of their REST API, which contains many updated and/or new methods to access the whole plethora of the functionality available on Github. Indeed, they have even gone as far as to release a desktop client for Mac’s, and for all I know are working on a Windows version, which would then render this effort of mine (because that’s what I’ve always intended) redundant.

So, despite not blogging about it, and despite going months between commits, I have been working on the library. The RestSharp git sub-module is gone (I mean, who likes sub-modules anyway?) in favour of the NuGet package. The authentication has been reworked slightly (still no OAuth yet) and the API is a little more fluenty.

Of course, it still doesn’t actually let you do very much, I mean even after a year, you still can’t perform all of the actions available to a user. This is terrible, and speaks volumes about me, as a person. Procrastination is my enemy.