Simple Web API OWIN host using F#

I thought it would be good to write a simple OWIN Web Api host using F# to show how easy it is to interop between the two languages and as a fun experiment. You can find all of the source code from this blog post at the FSharpWebApi github repository.

If you open the Program.fs solution in the github repository you will see the following two lines of code are reponsible for starting the web server:

let hostAddress = "http://localhost:8000"
let server = WebApp.Start(hostAddress, getAppBuilder())

The getAppBuilder function is defined in the WebServerBuilder module as follows:

let getAppBuilder() =
    let config = new HttpConfiguration()
    config.Routes.MapHttpRoute("default", "{controller}") |> ignore
    fun (appBuilder:IAppBuilder) -> appBuilder.UseWebApi(config) |> ignore

The getAppBuilder function returns a function with the signature (IAppBuilder) -> (). This signature is the same as the one expected by the first parameter of WebApp.Start. The reason for breaking this function off into its own module is so that it can be tested.

The cool thing about the Web Api Owin Self host stack is that there is a nuget package that allows you to test your server without going over http. This is great because it saves you all of the hassle of hosting an endpoint for your tests and tearing it down again. The test framework preserves all of the semantics so the requests will go through the same pipeline it’s just at the final moment they won’t go over http. The nuget package for this is Microsoft.Owin.Testing.

To use the Microsoft.Owin.Testing nuget package you have to call the static method TestServer.Create(IAppBuilder -> ()). You can see that the test server create method takes the same function that is returned by our getAppBuilder function. Which is the reason for isolating this code. The getAppBuilder function contains the logic for how your server will behave (routes, media formatters etc) so by pulling that out into a function we can test it.

As I’ve mentioned before testing in F# is very terse and to the point. Here is the full test suite for my simple hello world server:

module WebServerTests =
    let createTestServer = fun () -> TestServer.Create(new Action<IAppBuilder>(getAppBuilder()))

    let ``get /Hello should return "get - hello world"``() =
        let testServer = createTestServer()
        let client = testServer.HttpClient

            |> should equal "\"get - hello world\""   

    let ``post /Hello should return "post - hello world"``() =
        let testServer = createTestServer()
        let client = testServer.HttpClient

        client.PostAsync("/Hello", new StringContent("")).Result.Content.ReadAsStringAsync().Result 
            |> should equal "\"post - hello world\"" 

To test the web server you need to get the http client that hangs off of the test server (let client = testServer.HttpClient). This gives you a special http client that is wired up directly to your web server. We can now test that we get the correct responses when issuing a get or post request to /Hello.

It is a bit of a shame that there is not an implicit conversion from Action in C# to T -> () in F#. This is the reason that the create test server line at the top of the tests is ugly. We have to new up an action of IAppBuilder and pass our getAppBuilder function into the constructor to convert our F# “action” into a C# one.

The last piece of the puzzle to make the server work is the Hello controller which can be seen below:

type HelloController () =
    inherit ApiController()

    member this.Get () = 
            "get - hello world"

    member this.Post () =
            "post - hello world"

F# shines again. Look how easy and readable this controller class is. Even if you have never written a line of F# code I reckon you could have a pretty good guess at what this controller does. The member keyword is used to provide the semantics of exposing a public property or method. The reason we need the brackets is to cause it to become a method rather than a property.

Apart from the slight ugliness of having to convert from a F# function type to a C# Action type, it is much clener in my opinion to write the code in F#. There is so much less noise. Here is the equivilent HelloController in C#:

public class HelloController : ApiController
    public string Get()
        return "get - hello world";

    public string Post()
        return "post - hello world";

All of the brackets clutter up this simple class. The brackets do not add anything to the code they just help the compiler parse it.

As already mentioned all of the code is up on a github repository for you to view at your leisure. If you have any feedback, comments or questions I would be happy to hear from you.


6 thoughts on “Simple Web API OWIN host using F#

  1. Pingback: F# Weekly #46, 2015 | Sergey Tihon's Blog

  2. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1969

  3. Seems an unfair comparison at the end there, in C# 6 the controller methods could just be:

    public string Get() => “get – hello world”;

    public string Post() => “post – hello world”;

  4. Pingback: Les liens de la semaine – Édition #159 | French Coding

Leave a Reply

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

You are commenting using your 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