Scripting Visual Studio Mobile Center with F# and Swagger

One of my favorite things about Mobile Center is that everything it can do is exposed via their REST API, meaning that if the default experience doesn't fit the workflow you're going for, you can compose things yourself in any way you see fit. They were also nice enough to expose a Swagger definition as well, making it easy to explore.

The API is easy to use, but one of the other nice things about Swagger is that there are a lot of options out there for automatically generating client libraries from them. For example, NSwag is a handy one for generating C# and TypeScript clients. That's cool and all, but wouldn't it be cool if there was an F# type provider to make it even easier?

Good news: there is! Just install the SwaggerProvider package from NuGet and you're only a few lines away from glory. For those of you already familiar with F# and type providers this will all be very familiar, so this is for the rest of you who aren't. Stick around, magic is coming.


First, let's create the type:

let [<Literal>]Schema = "https://api.mobile.azure.com/preview/swagger.json"
type MobileCenter = SwaggerProvider<Schema>

Now if you hover over that MobileCenter type, you'll see that with just those two lines of code we've got a rich type defined for us:

SwaggerProvider went through the Swagger definition and created a comprehensive set of methods and types for us, making it dead simple to start interacting with the API in a typesafe manner with great intellisense. For example, to pull a list of apps in your account:

In addition to the method signatures we've also got strong types for the resource models as well, so we get intellisense and compile-time checks there as well:

It was also nice enough to reformat the property names to line up with normal .NET coding conventions: in the raw JSON AzureSubscriptionId is actually azure_subscription_id.

In order to query your account you'll also need to plug in your API key as a header to the request:

let mobileCenter = MobileCenter(CustomizeHttpRequest = fun req ->
    req.Headers.Add("X-API-Token: your-token-here")
    req)

This may not seem like much, especially since writing REST clients isn't particularly hard work, but things like this really lower the barrier to exploration in addition to providing great compile-time checks on your code against third-party APIs. In just a few lines of code you can start composing Mobile Center's features together any way you want, and if it compiles, you can probably bet that it'll work.