With HTTP, your application is your API

As of ASP.NET MVC 4.0, the once-named WCF WebAPI project is now part of MVC. To provide a quick summary for those not familiar with either of the two:

  • ASP.NET MVC is a framework that allows you to create applications based on HTTP.
  • WebAPI is a framework that allows you to create applications based on HTTP.

So now, under one roof (the roof being ASP.NET MVC not ASP.NET which would have made a bit more sense) you can use two distinct technologies to create HTTP-based applications. Note that I’m talking about HTTP, not necessarily what one would call RESTful systems, but plain HTTP.

Two choices, what to do?

Which one to choose from though? Well, the problem with that question (or maybe a somewhat answer) is that neither of the two technologies is complete. Each have their own missing features and benefits.

With ASP.NET MVC, out of the box, you don’t get things like Content Negotiation, Support for Conditional GETs or PUTs, Complete HTTP Response codes, HTTP Authentication, among other things. And in case you’re wanting to take a resource approach, well you’re out of luck there too since MVC is focused around operations not resources. You do get nice support for View Engines though.

On the other hand, with WebAPI, you do get some of the previous things, mainly Content Negotiation and a more Resource orientated approach (or so it has been said). You also get self-hosting capabilities and are more “exposed” to the raw HTTP. But, you don’t get a View Engine. What this means is that you can’t easily throw together some template in Razor and have it display to in a browser as a user interface.

The Microsoft Guidance

The general guidance coming out of Microsoft, be it from blog posts, tutorials or generally what members of the ASP.NET team are recommending, is to use the best of both worlds. That is, use MVC to create your user interface and use WebAPI to create your API. You can have a CustomerController to handle the HTML views and interaction with real humans, and have an CustomerAPIController (or whatever is may be called) to deal with non-human software interacting with your system. There are wizards in the product to create the different types of controllers and the main debate going on seems to focus more around what folder each type of controller should reside in. It is also mostly being defended under the Separation of Concerns Act.

To be clear, it is recommended to:

  • Create your user interface with MVC
  • Create your API with WebAPI

There is no division

When you’re creating an application based on HTTP, your application protocol, that is the language that is used to communicate between your application and the consumer of your application is HTTP. HTTP is not a mere conduit to transfer information. It is a fully fledged application protocol.  It has operations, it has request headers, it has responses and response code. It knows how to deal with stale data, it knows how to deal with authentication. It knows what resources are and how to represent these in different way. It is your API.

If you take this into account, your User Interface, is nothing more than another consumer of your API. When you request to see a Customer, if you are a human being, you will be presented with an HTML page to see the customer record. When you are a machine you can request a JSON or XML variant of that customer. However, these are merely two different representations of the same thing. When you update  a customer, be it via a user inputing data into a form, or a machine submitting a POST request, there should be no distinction in the behavior of your application. Why would there by? And if there isn’t, why add an extra overhead of separating them out? It makes no sense whatsoever to try and artificially separate these two concepts out into UI and an API. The only UI thing you need to do on the server is forms and HTML pages. Not separate controllers.
Well there are two potential reasons you might want to do this:

  • Political, to somehow justify having two ways to implement the same thing
  • Technical. Shortcomings of one technology prohibiting you from doing it

But neither of those stand. The political reason here should be irrelevant to you as a consumer of the ASP.NET MVC stack. More importantly however, the technical reason should not distort the reality.

So what should you do?

Personally I am against drawing this artificial non-existing line between the two concepts merely to justify technical shortcomings. The solution I would take is to have one API and use one of the two technologies, or if you’re open to alternatives, use those (OpenRasta, Nancy, FubuMVC), whatever,  I don’t care which one you use.

I have been using MVC for some years and the missing pieces such as content negotiation, HTTP authentication, ETag support (conditional requests), are nothing but a bunch of filters that are implemented with a few lines of code. Moving from operations to resources is nothing but a few routing techniques, implemented using some conventions (if you’re interested I have a lot of code I can share).

Whatever you do use though, don’t let its shortcoming dictate your design. You are implementing HTTP systems, embrace HTTP.

15 thoughts on “With HTTP, your application is your API

  1. jfromaniello

    I agree! Embracing http for me means using something close to the metal. An API like nancy is what works for me

    Reply
  2. Santos Ray Victorero,II

    I kind of disagree with your definitions!

    ASP.NET MVC is a framework that allows you to create USER-DRIVEN applications based on HTTP.

    (Any) Web API is a framework that allows you to create MACHINE-TO-MACHINE applications based on HTTP.

    I agree that it should be easier to return “Views” (Forms or Custom Data) but that could be customized using a custom MediaTypeFormatter

    Reply
    1. hhariri Post author

      Then you disagree with my post also, because my point is that there is no difference between an end-user application and a machine-to-machine, when leveraging HTTP.

      Reply
      1. Santos Ray Victorero,II

        No the whole post ;-), I agree that there is some duplication in the specific implementation & maybe a future “hybrid” will be better.

        But the way that I see it (I could be wrong) is that MVC as a presentation pattern is “representing” the client UI (User-Driven) & the Web Api “represents” ReST & the Http Protocol (Machine-to-Machine) .

  3. hhariri Post author

    @Santos,

    Yes. MVC is a presentation pattern, but both MVC and WebAPI are frameworks that are based on HTTP and what I’m saying is that, when embracing HTTP, there is no difference between UI and API. That is the point of the post, not comparing the technologies.

    Reply
  4. tgmdbm

    Hey Hadi,

    I’m interested in seeing the code you mentioned. Currently using RestfulRouting but something more convention based would be great.

    Cheers

    Reply
  5. tgmdbm

    Hi Hadi

    I’m interested in the code you mentioned. I’m currently using RestfulRouting but something more convention based would be Great.

    James

    Reply
  6. Pingback: Herding Code 141 – Lightning Round with Hadi Hariri

  7. Vinney Kelly (@vinneyk)

    I really like this concept. REST is a very new monster to me but this just seems like the right implementation of the pattern. Thanks for having the courage to say “I think this is wrong!”

    P.S. It would be great if you would add the link to your code in the body of the article.

    Reply
  8. Filip W (@filip_woj)

    Hadi, it seems that you base the entire discussion on this statement: “the roof being ASP.NET MVC not ASP.NET which would have made a bit more sense”

    And that, in my humble opinion, is fundamentally wrong. Web API is not tied to MVC in any way, nor it is a subset of MVC.

    It’s a standalone framework and MVC (or actually, ASP.NET to be correct) is just one of the contexts in which it can run.

    From a broader perspective you can distinguish three of those contexts:
    – web, so on top of ASP.NET – be it Web Forms or MVC. Actually using OWIN, it doesn’t even need IIS
    – self host – pretty much anywhere where you have at least .NET 4 and access to HTTP protocol i.e. Console apps, WPF apps, Metro apps, Windows services and so on
    – memory host – temporary host running in memory without consuming ports

    While I see your point about uniting what MVC and WebAPI offer, if that was done, none of the non-web options would be available any more. Unless of course, you mean that we should drag MVC and all its dependencies (System.Web and all that) to other, non-web contexts.

    The way I see it (and from what I heard), I think MVC vNext will be redesigned to have more in common with Web API than it currently has. The fundamentals laid by Web API give the ASP.NET web stack a modern HTTP object model, which was one of the biggest flaws of MVC (mainly the old HttpContext).

    Reply
    1. Hadi Hariri Post author

      My entire point isn’t based on the roof being ASP.NET. I said it would have made slightly more sense. My point is that there is an artificial divide which is a consequence of having created a new product instead of evolving an existing one and that is justified (as always) with the “backward-compatibility” stance. To say that Web API is a more modern approach to web development is utter nonsense. Request/Response and HTTP is the heart of HTTP and has always been. To say that they couldn’t touch MVC because it’s legacy is also utter nonsense if they already consider something so new, so old.

      Reply
  9. Filip W (@filip_woj)

    Hadi, I think you misunderstood my comment (and perhaps, as you suggest, I misunderstood, s oat least that’s something we could agree on 🙂 )

    What I am trying to say is that what Web API brings to the table is a more modern approach to HTTP in the .NET context. The HTTP object model representation in Web API (HttpRequestMessage/HttpResponseMessage, HttpMessageHandler, HttpContent and such) is much better designed, lightweight and way more semantically robust than the old HttpContext and the baggage its been dragging from .NET 1.1 – and which is something MVC is built around (yes it’s new as a framework, but in the pure HTTP area it is far far from perfect).

    The Web API HTTP object model is going to be the foundation of HTTP communication in .NET onwards, and it will probably be adopted by MVC at some point. Whether it should have been adopted by MVC4 already, that’s another story – I think it’s more of a timing and product lifecycle issue.

    Moreover, my understainding is that it all came down to (and that’s something that has been reiterated by the product team) deciding whether to design the new HTTP object model for .NET from scratch or whether to squeeze it into MVC HttpContext constraints (it would have to, in order to prevent breaking changes).

    On a side note, I completely agree with your notion to “embrace HTTP.” In fact, as you brilliantly point out, “text/html” is just one of the media types and HTTP systems (including the popular RESTful applications) are supposed to serve different media types based on the requestee’s wish, be it “application/json”, “text/html” or “text/plain” or anything else.
    In that sense, I think it’s very interesting to see community initiatives such as Razor media type formatter, which, at some point in their maturity, would perhaps (?) allow you to provide your entire application off Web API for both “machines” and “human”.

    The good thing about ASP.NET Web stack, is that it’s open source and it’s really listening to the community feedback. These days, for a change, developers have a chance to shape up the Web stack products’ direction and I’m sure, out of all people, they’d value your feedback extremely high.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s