Posts Tagged ‘REST’

Custom filters in AngularJS

February 23, 2016 Leave a comment

In this post I am going to show you how easy it is to write custom filters in AngularJS and for the simplicity of the demo I am going to display a list of cron-jobs in a tabular data. Each job has details like the Id, action etc. and has a status which is represented in numbers like 0,1,2 etc. This may be suitable from a storage or system point of view but is not that user-friendly, so lets write a custom filter to transform numeric values into user-friendly status.

First we start with an AngularJS controller "CronJobsController" and it will be responsible for calling the cronjobs ASP.NET Web API.If the call is successful the returned data is assigned to $ object so that we can bind the data to our view.


var app = angular.module('mainApp', []);
app.controller('CronJobsController', function ($scope,$http) {
    $ = [];
        method: 'GET',
        url: '/api/cronjobs'
      .then(function(response) {
        $ =;
      },function(reason) {
        $scope.error =;

Next step is to wire up the "myApp" to the HTML page by using the ng-app directive.


<body ng-app="mainApp">
    <!--Html omitted for brevity -->

Now I am going to create the view by adding some table mark-up and use bootstrap to format the HTML table. For data binding I’m going to use the ng-repeat directive to enumerate through the jobs and bind the data to the table.


<div class="row">
    <!-- Jobs Controller Scope -->
    <div class="col-md-12" ng-controller="CronJobsController">
        <table class="table table-striped">
                    <th>Correlation Id</th>
                <tr ng-repeat="job in jobs">
                    <td>{{job.created | date:'dd-MM-yyyy'}}</td>

    <!-- End of Jobs Controller Scope -->

Lets run the application and we can see that everything is working perfectly.

Cron Job Display Data without filter

Now we are going to build our custom filter "status" which will return a user-friendly status based on the numeric value.


/// <reference path="app.js" />

app.filter('status', function() {
    return function(status) {
        switch(status) {
            case 0:
                return "Not Started";
            case 1:
                return "In Progress";
            case 2:
                return "Completed";
                return "Unknown";

Nothing special here a simple switch case statement returning user-friendly text and all is left is to apply this filter to our model’s status property as shown in below code snippet.

<td>{{job.status | status}}</td>

And after applying the filter we can see the user-friendly status is displayed instead of the numbers.

Cron Job Display Data with filter

It’s a very simple yet powerful feature and another reason to love AngularJS.


Designing Web API Versioning

May 31, 2015 3 comments

In this post I am going to talk about some of the commonly used Web API versioning strategy and hope it will help you decide which one is best suitable for your scenario.You will also see that there is no right or wrong way of designing them but I am always about options and different approaches, ultimately it is you who have to decide which approach is best suitable for you.

Uri based approach:

In this type of versioning strategy the versioning is embedded in the URI and probably the most popular one.However I personally think it is quite anti-REST as with each version the URI changes. REST is very resource oriented and it means once you have defined the URI(address) to the resource then it shouldn’t change just because you have a new version of that resource. This also means that the physical URI surface area will increase in terms or URIs and the number of deployments.

Lets take a look at an example


As you can see when a new version v2 is released the URI for the user resource will change and lot of your clients will have to point the URI to The clients will have to keep up with your latest version if they prefer to use your latest version all the time. There is no easy way to make the version optional and return the latest version but in terms of ease and implementation it is the best approach.

Query string based approach:

In this type of strategy the versioning is appended as a query string and it is quite popular too. The version is passed as a query string so the URI doesn’t change when the version is changed, however make sure you are very clear on how you will handle versioning when the versioning is not provided.


But consider this that the query string parameter is optional, so what would happen if somebody request it as Do you return the oldest supported version or do you always return the latest version. There is no easy answer to this and depending on your requirement and how you foresee your Web API’s changing you might choose one over the other.

In my personal experience always return the latest version as this will allow your API consumers to either stick to the older version by specifying the version number or deal with the latest version if there are any breaking changes.

Content Negotiation based approach:

This is my favorite one and is getting slowly popular and in my opinion more REST than the above two.In this strategy the version is passed as content negotiation header. This way the version doesn’t appear nor in the URI or in the query string and the client doesn’t have to really change much to keep up with your latest version. However you still have to decide how do you handle the default versioning when no version is specified as part of content negotiation.


Where the "1.0" at the end specifies the version and the application/vnd specifies it is a vendor specific header. Another thing I have noticed is that some people because of ease pass the version in the "Accept" header even if it is an HTTP POST or PUT. I think if you are going down this path then make sure "Accept" is for GET and "Content-Type" is for POST or PUT.


And this is how the POST will look like.



Custom Request Header based approach: Last but not the least is using a custom “x-*” header to specify the version and specifying a date as the version. This is something I noticed when I first started looking into your Azure Service Bus and how the QueueClient and TopicClient build the version header into their request. I guess this is a trend Microsoft have started and you can see it across the Azure Platform. I really like this approach and may be in my next project I’ll get a chance to implement it.



Another aspect of the Web API versioning design is that, how many versions should you keep on supporting and like many software philosophies there is no definitive answer. In my experience maintaining and supporting multiple versions of Web API can be very complex,error prone, at times cruel and can prove very costly (both financially and mentally). So make sure you are designing it correctly and your upper management understand the complexity behind deployment, bug fixes, writing and fixing test etc while you are supporting so many versions. The general rule of thumb in my personal experience is to only support 2 versions of any given resource. Also make sure you have clear strategy of maintaining versions for related resources.

Deprecating older versions:

The simplest way to inform the clients that the version they requested for a resource is deprecated is by adding a “Deprecated” header with a value “true” to the response. Let say that the request from the client for a product with id 1234 is something like this.



Then the return response should be


HTTP/1.1 200 OK
Content-Type: application/json; version=1
Deprecated: true
{"id":"1234", "name":"Brown Rice", "trade-number":"99804169"}


I hope this post has given some insight into the Web API versioning and in the next post I’ll show some code to show how this all comes together.Happy versioning !!! 🙂

OWIN and Web Api

November 30, 2014 Leave a comment

In this post I am going to talk about how to get started with WEB API project with OWIN . As usual I am going to start with File > New Project > ASP.NET Web Application > Empty Solution and run the following Powershell command to get all the necessary OWIN packages from nuget.

PM> Install-Package Microsoft.AspNet.WebApi.Owin
PM> Install-Package Microsoft.Owin.Host.SystemWeb
PM> Install-Package Microsoft.Owin.Diagnostics

As you may have noticed the second package is to run OWIN Middleware on IIS but you could easily change that to "OWIN Self host" and spawn the web api on a console application with no dependencies on IIS.

The primary motivation and goals of OWIN specification is to develop web application which are independent of Web Server technology like IIS. Another goal is to move away from the System.Web.dll as it’s a 13-year-old assembly. That time it served it’s purpose as it was designed mainly keeping ASP.NET Web Forms in mind but now has a lot of dead weight when it executes code. We still can’t get away with it but in the ASP.Net vNext it is gone and your web application will run faster and will scale better.

For more information on OWIN please visit the website.

Anyways back to OWIN, now we are going to write a start-up class which the OWIN runtime will use it to bootstrap our web application and this is how the start-up code looks like.


public class Startup
    public void Configuration(IAppBuilder app)

This is how the OWIN pipeline identifies the startup routine with the above method signature. As you can see it takes an interface IAppBuilder in which you can plug your own middleware and in the above code we are plugging the welcome page middleware component to display the page. This is the pattern which is used in development where you will develop your own middleware and plug that into the app builder.

Now when we run the application we can see the OWIN "Welcome page "running using IIS Express.

Owin Startup Page

In the next step I am going to add a simple Customer Controller as shown below.


public class CustomerController : ApiController
    private List<Customer> customers;

    public CustomerController()
        customers = new List<Customer>();
        for (var i = 0; i < 3; i++)
            customers.Add(new Customer
                Id = i,
                FirstName = "First" + i,
                LastName = "Last" + i

    // GET: api/Customer
    public IEnumerable<Customer> Get()
        return customers;

    // GET: api/Customer/5
    public Customer Get(int id)
        return customers.FirstOrDefault(c => c.Id == i);

    // POST: api/Customer
    public void Post(Customer customer)


    // PUT: api/Customer/5
    public void Put(int id)


    // DELETE: api/Customer/5
    public void Delete(int id)

So the controller code is done and let’s wire up the controller into the OWIN pipeline by adding the HttpConfiguration to the OWIN start-up class which has the routing configuration.

Here is the complete start-up class code.


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

           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional });


Lets do some quick tests in order to see if everything is working correctly. I am going to use the POSTMAN extension for Chrome and will execute following GET request.


and with no surprises here is the result of 2 request.

Customer Web Api with Get

Customer Web Api with Get specific customer

As you can see it is fairly simple to set up OWIN and start using it in a Web api application. Moreover, there are 2 more ways to define the OWIN start-up class. First either you can decorate your with assemblu attribute as shown below

assembly: OwinStartup(typeof(OwinTestingDemo.Startup))]

or you can define it in your web.config as

  <add key="owin:appStartup" value="OwinTestingDemo.Startup" />

The choice of different startup may come handy in case for different environment you may want to run different middleware components.

That’s it for now and in the next post I am going to show how we can simplify testing web api with OWIN.