Hosting options for WebAPI

So you’ll probably be using IIS to run your WebAPI apps, but you really don’t need to. WebAPI ships with a class which starts a web server handling WebAPI requests, in System.Web.Http.SelfHost..dllHttpSelfHostServer.

Now, this is really interesting, for two reasons.

1) You can spin up a new server, run some tests against it, and shut it down. That means you can test all your HTTP traffic without having to set up a development server. I struggled with this all last week — how do you write a test to prove all your HTTP code is working, but not require all your developers to set up a web server like http://localhost:3000/myapp just so that you’ve got somewhere to act as an endpoint for calls? This short-lived server becomes your endpoint for the lifecycle of the tests.

2) It allows you to create a host outside IIS, on a non-server machine. For instance, imagine you were writing a document search application. It has a front end written in Windows Forms, and the backend is written in WebAPI. When you start the app, it starts an HTTP server at http://localhost:1234/mydocumentsearch. The front end loads its data by making GET requests to that server, and saves changes by POSTS and PUTS and DELETES. Now let’s say you want to search the corporate network using the same app. It would be simple to change the URI to http://corporateserver/documentsearch and now the same app, with no code changes, has become a corporate intranet-based application. Change it again to http://www.internetdocuments.com/search and it’s now an internet-enabled cloud-whatsit buzzword-filled bundle of awesome. And you don’t need to recompile to switch between these seriously different modes.

This approach says — code for HTTP first, and in fact only code for HTTP. You don’t need any other kind of public API. You don’t need an API that you compile into your app, but instead you really code in separate tiers communicating through HTTP. You can now code everything as if it were cloud-enabled, and then just switch to the cloud when you’re ready.

For me, it’s the testing scenario that’ll be most useful in the short term, but the other one is making me think about API design. After all, there are now even database engines (like CouchDb) which only offer HTTP/JSON interfaces. HTTP has become a universal communication mechanism. Will this become the widespread pattern of the future?

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 )

Facebook photo

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

Connecting to %s