ServiceStack: New API – F# Sample (Web Service out of a web server)


Two weeks ago in F# Weekle #6 2013 I mentioned Don Syme’s “F# + ServiceStack – F# Web Services on any platform in and out of a web server” post. There were two samples of  using ServiceStack from F#. One of these examples is given on ServiceStack wiki page in Self Hosting section. It is also detailed in Demis Bellot’s “F# Web Services on any platform in and out of a web server!” post.

Unfortunately, this example is already obsolete. Some time ago, ServiceStack released a brand new API that significantly changed programming approach, especially routing (for details see “ServiceStack’s new API design“). But I am happy to say that you can find an updated example below!

New design is more typed. In the previous version IService‘s methods returned the Object, but now Service returns concrete type that is defined by IReturn<T> interface of request message.

open System
open ServiceStack.ServiceHost
open ServiceStack.WebHost.Endpoints
open ServiceStack.ServiceInterface

[<CLIMutable>]
type HelloResponse = { Result:string }

[<Route("/hello")>]
[<Route("/hello/{Name}")>]
type Hello() =
    interface IReturn<HelloResponse>
    member val Name = "" with get, set

type HelloService() =
    inherit Service()
    member this.Any (request:Hello) =
        {Result = "Hello," + request.Name}

//Define the Web Services AppHost
type AppHost() =
    inherit AppHostHttpListenerBase("Hello F# Services", typeof<HelloService>.Assembly)
    override this.Configure container = ignore()

//Run it!
[<EntryPoint>]
let main args =
    let host = if args.Length = 0 then "http://*:8080/" else args.[0]
    printfn "listening on %s ..." host
    let appHost = new AppHost()
    appHost.Init()
    appHost.Start host
    Console.ReadLine() |> ignore
    0

For comparison, the previous version is:

open System
open ServiceStack.ServiceHost
open ServiceStack.WebHost.Endpoints

type Hello = { mutable Name: string; }
type HelloResponse = { mutable Result: string; }
type HelloService() =
    interface IService with
        member this.Any (req:Hello) = { Result = "Hello, " + req.Name }

//Define the Web Services AppHost
type AppHost =
    inherit AppHostHttpListenerBase
    new() = { inherit AppHostHttpListenerBase("Hello F# Services", typeof<HelloService>.Assembly) }
    override this.Configure container =
        base.Routes
            .Add<Hello>("/hello")
            .Add<Hello>("/hello/{Name}") |> ignore

//Run it!
[<EntryPoint>]
let main args =
    let host = if args.Length = 0 then "http://*:1337/" else args.[0]
    printfn "listening on %s ..." host
    let appHost = new AppHost()
    appHost.Init()
    appHost.Start host
    Console.ReadLine() |> ignore
    0

Update: An example of ServiceStack New API for F# 2.0 users. F# 2.0 does not have val keyword / auto-properties which were used in the first example.

</pre>
open System
open ServiceStack.ServiceHost
open ServiceStack.WebHost.Endpoints
open ServiceStack.ServiceInterface

type Project() =
    let mutable projectID = 0
    let mutable projectName = ""
    let mutable companyName = ""
    let mutable projectStatus = ""
    member this.ProjectID with get() = projectID and set(pid) = projectID <-pid
    member this.ProjectName with get() = projectName and set(pn) = projectName <- pn
    member this.CompanyName with get() = companyName and set(cn) = companyName <- cn
    member this.ProjectStatus with get() = projectStatus and set(ps) = projectStatus <-ps

type ProjectResponse() =
    let mutable projects = List.empty<Project>
    member this.Projects with get() = projects and set(pr) = projects <- pr

[<Route("/Project/{ProjectName}")>]
type ProjectRequest() =
    let mutable projectName = ""
    interface IReturn<ProjectResponse>
    member this.ProjectName with get() = projectName and set(n) = projectName <- n

type ProjectService() =
    inherit Service()
    member this.Any (request:ProjectRequest) =
        ProjectResponse(
             Projects = [Project(ProjectName=request.ProjectName, ProjectID=1, CompanyName="A")])

//Define the Web Services AppHost
type AppHost() =
    inherit AppHostHttpListenerBase("Project F# Services", typeof<ProjectService>.Assembly)
    override this.Configure container = ignore()

//Run it!
[<EntryPoint>]
let main args =
    let host = if args.Length = 0 then "http://*:8080/" else args.[0]
    printfn "listening on %s ..." host
    let appHost = new AppHost()
    appHost.Init()
    appHost.Start host
    Console.ReadLine() |> ignore
    0
<pre>
About these ads

19 Responses to ServiceStack: New API – F# Sample (Web Service out of a web server)

  1. There seems to be a typo on line 11 in the word “Response”:
    “interface IReturn”
    Minor detail, but it could cause confusion for copy/pasters.
    Otherwise thank you for the example :)

    • Sergey Tihon says:

      Thanks. Fixed. This is a strange typo… =)

  2. Yan says:

    Hey, the response types are made mutable so that they can work with the ServiceStack.Text serializer I presume? You can also mark them with [CLIMutable] and make them compatible with ServiceStack.Text.

    • Sergey Tihon says:

      Yes, thanks. Actually, good idea! Sample was updated.

  3. Pingback: Scott Banwart's Blog › Distributed Weekly 196

  4. Pingback: ServiceStack: F# Client Application | Sergey Tihon's Blog

  5. Pingback: F# Weekly #9, 2013 | Sergey Tihon's Blog

  6. Mr. D says:

    Hi
    I am trying to run New API code in F# .Old code works fine but i get “Unexpected keyword ‘val’ in member definition” (Line 13 in code above)

    Can you please suggest me what is that not right ?

    I have a service running (New API) with C# . I want to convert this to F#

    Thanks in advance.

    • Sergey Tihon says:

      Can you clarify what version of F# and .NET you use?
      The ‘val’ keyword is a part of F# 3.0 (which ships with Visual Studio 2012)
      If you are using older version of F# you should replace Hello class definition to the following

      type Hello() =
      let mutable name = ""
      interface IReturn<HelloResponse>
      member this.Name with get() = name
      and set(n) = name <- n

  7. Mr. D says:

    Hi
    Thanks for the quick response .
    I am using VS2010 Ultimate and I have VS2012 Web Express ( i am not sure if i can use F# there)
    The code you sent also doesn’t work.This has no Response type in IReturn and gives other errors.

    Here is my code i want to port from c# to F# (With a list of project object) Can you please explain how i can write that in F#2.0 and what would be best way to make F# 3.0 up and running

    [Route("/Project/{ProjectName}")]
    public class ProjectRequest : IReturn
    {
    public string ProjectName { get; set; }

    }

    public class Project
    {
    public int ProjectID { get; set; }
    public string ProjectName { get; set; }
    public string CompanyName { get; set; }
    public string ProjectStatus { get; set; }

    }
    public class ProjectResponse : IReturn<List>
    {
    public ProjectResponse()
    {
    Projects = new List();
    }
    public List Projects { get; set; }

    }

    • Sergey Tihon says:

      >>The code you sent also doesn’t work.This has no Response type in IReturn and gives other errors.
      Sorry, it is comment formatting issue (already fixed)
      >> I have VS2012 Web Express ( i am not sure if i can use F# there)
      You can! http://blogs.msdn.com/b/fsharpteam/archive/2012/09/12/announcing-the-release-of-f-tools-for-visual-studio-express-2012-for-web.aspx
      >> what would be best way to make F# 3.0 up and running
      Please look at available options: http://fsharp.org/use/windows/
      >> Can you please explain how i can write that in F#2.0
      You code should look like this: https://gist.github.com/sergey-tihon/5343737

      • Mr. D says:

        Thanks alot . I will try this and will bother you again in case i have more question ;)

        thanks again.

      • Mr. D says:

        Your code works like a charm. I hope with F# 3.0 code will look more cleaner .

  8. You likely wont need all that boilerplate for the F# 2.0 solution and can benefit from setting ServiceStack’s text serializers to serialize public fields with:

    JsConfig.IncludePublicFields = true;

  9. Mr. D says:

    HI
    I have upgrade my service to F# 3.0
    I was using Dapper a lot in Service Stack C# service .What would be the best option to use it in F# solution?
    Do i have to use it via creating a seprate c# assembly and call in from F# ?? Or there are better solution.

    Thanks for your previous help again.I have almost reduced my service code to over 50% less line of code and in almost no time :)

    • Sergey Tihon says:

      F# should be good with Dapper too, I think that you can rewrite it with F# if you wish – http://stackoverflow.com/questions/9364480/dapper-dot-net-query-in-f
      BTW, Dapper use F# PowerPack under the hood ;) // https://code.google.com/p/dapper-dot-net/source/browse/#git%2Fpackages%2FFSPowerPack.Community.2.0.0.0

      • Mr. D says:

        thanks , i will have a look to it. may be i can rewrite dapper completely in F#

  10. Mr. D says:

    Hi
    I could look for the possibility to transform dapper into F# but this could take a while .
    I read little about FSSQL but could find any analysis about performance etc ..

    http://d4dilip.wordpress.com/

  11. Pingback: Service Stack service in F# outside Web server | D Says

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: