Menu

Who is HAL?

By Matt Rees

Here at Eden Agency we’re firm believers in the API First methodology. "What’s that!?" I hear you cry, well let me care to explain. An Application Programming Interface (API) is a defined set of methods, published by your software, that easily allows other software to connect with it.

But why is that good?

Let me give you an example say you had a new website built and then 6 months later you decide to expand your digital empire to include a mobile app that uses the same data. Chances are to minimise costs on the original build the website doesn’t share it’s data, or expose an API, as this was “out of scope” (every project managers favourite phrase). So to get the app to connect with the website you have the added cost of going back to the website updating that as well as creating your shiny new app.

API First

With API first that headache is almost all but eradicated. The API is developed first and clearly defines the data and methods that are currently available. So the initial website connects to that and then in 6 months when your great new mobile app is ready to be built that too can connect to the same API. Then if further apps (web, mobile or some mysterious platform that is yet to exist) or 3rd party products want to consume your data the API is there as the brain of the system serving data to all the platforms.

API First

So what’s all this HAL talk about?

At Eden Agency for our web projects we’re firmly in the .NET camp. They’ve got some great tools for web development and recent developments withOWIN (Open Web Interface for .NET), Rosalyn and the open sourcing of the .NET language itself it’s massively expanding what developers can do as well as reducing licensing costs, but I digress. One of these tools is the great NuGet package manager which lets us download lots of awesome libraries other smart developers have created and decided to share out of the goodness of their heart.

A great example is WebApi.Hal. HAL (Hypertext Application Language) is a specification to standardise and simplify the transfer of data between systems. Have I lost you again? When sharing data between systems via your shiny new API you request some data and the API sends it back. Fantastic but wouldn’t it be great if you knew the format of the data and what you could do with it? That’s what HAL aims to do. Imagine it as an email. When you receive your email it’s in a standard format, you know where to look to see who sent it to you, where to look to see the body or the subject. You also know what you can do with the email (reply, forward, delete).

HAL aims to do that by standardising the response from your API into 2 distinct areas: Resources and Links.

Resources can contain 3 things:

  • State - this is the information your requested.
  • Links - this is a set of URIs that let you know where you can move next in the system with the data you’ve requested.
  • Embedded - a useful place to embed further information (normally sub resources) that may be handy to quickly expand on your requested data.

As you can see Links are actually found within resources and contain 3 things:

  • Target - the URI itself.
  • Relation - a lookup value to quickly find the target, for example next or previous if you wanted to move back or forward through a list.
  • CURIEs- Help. Quite literally this is where you can provide a link (a Link within a Link, it’s like Link Inception) so that if someone can’t understand something about this request they can quickly look it up.

So now I’ll give you a whirlwind tour of how to set up HAL in your project. We’ll be using a .NET Web Api 2 project in Visual Studio 2013 which by default comes with OWIN set up but this tutorial won’t go through that in this tutorial, I’ll save that for a later date.

Firstly install WebApi.Hal via NuGet. Right click on the references icon in your solution explorer chose NuGet and search for the library in the search bar.

Nuget Package Management Dialog

This will also install any dependencies including Newtonsoft.JSON. The only thing we’re going to have to do in the OWIN pipeline is create some media formatters, these define what data format the API can send and receive. There are two very popular lightweight languages for transferring data around systems quickly and efficiently, XML and JSON. The WebApi.Hal library can handle both but no matter how much Microsoft want me to use XML, JSON is a far more convenient language and even more conveniently the Newtonsoft.JSON library installed as a prerequisite allows us to do that!

In a web project that implements the OWIN specification the entry point into the system is always the Startup class, or a class decorated with the Startup attribute. Microsoft have their own implementation of the OWIN specification (confusingly called Project Katana) which uses the Startup class and a method called Configuration.This method has a parameter, an IAppBuilder object. This IAppBuilder object allows us to plugin middleware to our system so other projects can handle different tasks such as authentication or authorisation. We’re going to tell the pipleline that this is a Web Api project and these are the configuration settings, including the Http routes (this is a familiar concept if you’ve ever done any Web API or .NET MVC projects) as well as adding in our media formatters.

public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            // Add content type formatters.
            config.Formatters.Clear();
            config.Formatters.Add(new JsonHalMediaTypeFormatter());
            config.Formatters.Add(new XmlHalMediaTypeFormatter());
            config.Formatters.Add(new JsonMediaTypeFormatter());

            config.Routes.MapHttpRoute("Api", "{controller}/{id}");

            config.MapHttpAttributeRoutes();

            IContainer autofacContainer = ConfigureAutoFac(config);
            app.UseAutofacMiddleware(autofacContainer);
            app.UseWebApi(config);
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }

You'll also notice I’ve plugged in another piece of middleware calledAutofac. This is our Inversion of Control (IoC) container and will handle dependency injection. The interface based design concept is prevalent in a lot of .NET projects and I’ll be using it to define how to interact with my data layer. For example my data will be held on a SQL Server instance but if I wanted to switch to Oracle, MySQL, NOSQL or any other database provider all I would have to do is create a new object that implements my interface and update my IoC container. I wouldn’t have to change any code anywhere else in the project, it would just work without causing any breaking changes or need for further development. You use an interface object in your code and then the IoC container will inject which implementation to use at runtime but we will see that later. I’ve also created a Data project using Code First design to quickly create a data layer but that’s out of scope of this tutorial…

So we have a data layer and a way to pull objects from the database, now we need to shape those database records into our standard HAL object or Representation. A Representation is the object provided by the WebApi.Hal library that we subclass which will quickly allow us to create our state, links and embedded resources. We create the Rel in the constructor of the object and override the CreateHypermedia method in which we set the Href property. This is key as it creates a self link which gets added to the representation and denotes how you got to where you are in the system.

public class UserRepresentation : Representation
    {
        public UserRepresentation()
        {
            Rel = LinkTemplates.Users.User.Rel;
        }

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        protected override void CreateHypermedia()
        {
            Href = LinkTemplates.Users.User.CreateLink(new {id = Id }).Href;
        }
    }

You’ll notice my links are all stored in a static class called LinkTemplates. This isn’t essential but it is a really tidy way to group all your links together which could come in handy if for instance you needed to quickly update all your links at once if you needed to move them to a subdomain.

public static class LinkTemplates
    {
        public static class Users
        {
            public static Link User { get { return new Link("User", "~/User/{id}"); } }

            public static Link NextUser { get { return new Link("Next", "~/User/{id}"); } }

            public static Link PreviousUser {get { return new Link("Previous", "~/User/{id}"); }} 
        }
    }

You can also add further links in the CreateHypermedia. When defining a new link if the URI contains variable data we wrap that in curly braces, then when we create the link we pass in an object containing a reference to whatever we wrapped up.

public static Link NextUser { get { return new Link("Next", "~/User/{id}"); } }
Links.Add(LinkTemplates.Users.NextUser.CreateLink(new { id = user.Id + 1 }))

Now we have set up our pipeline, created a data layer and defined our HAL representation all that’s left is to create the method to GET this data. In the controllers folder I added a User controller and created a GET method that follows the route we defined earlier in our Startup class. You can see here in the constructor we are injecting in an instance of IDataContext, we’re not fussed that it’s a SQL instance - our IoC Container will handle that, all we need to know are the methods we can use. We then pull our database record, use it to populate a new instance of the user representation and then here I’m creating further links. I did it in my controller method as I have a reference to the overall number of data records and can write my simple logic but it’s probably tidier to normally write further links in the CreateHypermedia method. We then simply return the UserRepresentation.

public class UserController : ApiController
    {
        private IDataContext DataContext;

        public UserController(IDataContext dataContext)
        {
            DataContext = dataContext;
        }

        public UserRepresentation Get(int id)
        {
            var user = DataContext.Users.FirstOrDefault(u => u.Id == id);

            var userRepresentation = new UserRepresentation()
            {
                Id = user.Id,
                FirstName = user.FirstName,
                LastName = user.Surname
            };

            if (user.Id < DataContext.Users.Count())
            {
                userRepresentation.Links.Add(LinkTemplates.Users.NextUser.CreateLink(new { id = user.Id + 1 }));
            }

            if(user.Id > 1)
            {
                userRepresentation.Links.Add(LinkTemplates.Users.PreviousUser.CreateLink(new {id = user.Id - 1}));
            }

            return userRepresentation;
        }
    }

To test all of this if we run the Web Api project we won’t see anything, this makes sense as my basic project doesn’t contain a front end. So simply either go to yoururl/user/1 or use your favourite HTTP tool, Fiddlr, Postman etc and create a GET request to the url and you should see your HAL representation with the data about that object and some links about where else to go next in the system.

{
    "Id": 1,
   "FirstName": "Matt",
   "LastName": "Rees",
   "_links":
     {
       "self":
        {
           "href": "/User/1"
        },
        "next":
        {
           "href": "/User/2"
        }
      }
}

Overall API First and HAL are all about future proofing your digital strategy and looking at reducing costs. Right now your digital strategy might be in it’s infancy, or it may have a well defined roadmap, but having one core system that serves existing and future products will reduce costs, simplify future developments and streamline maintenance.

comments powered by Disqus

We’re a top UK digital agency - wahoo!

By Sophie Hardbattle

We're Eden Agency - one of the UK's top digital agencies.

Read more

An Introduction to Building a SpriteKit-UIKit Hybrid App

By Alan Chung

A guide to help you get started on making an iOS app that seamlessly combines the visual punch of SpriteKit with the practicality of UIKit.

Read more

How to build a material design prototype using Sketch and Pixate - Part Three

By Mike Scamell

Part three of a three-part tutorial on building a material design prototype. This section focuses on adding more detail to the prototype in Pixate.

Read more

We're Hiring - Web Developer Role

By Craig Gilchrist

We are currently seeking a full time full-stack web developer to join the team at our Knaresborough office.

Read more

How to build a material design prototype using Sketch and Pixate - Part Two

By Mike Scamell

Part two of a three-part tutorial on building a material design prototype. This section focuses on creating a interactive login screen in Pixate.

Read more