Search code examples
httpf#type-providersf#-data

How can the JsonProvider be used with URLs requiring authentication?


I want to do something very similar to what's shown in the docs for FSharp.Data:

enter image description here

The URL I'm requesting from though (TFS) requires client authentication. Is there any way I can provide this by propagating my Windows creds? I notice JsonProvider has a few other compile-time parameters, but none seem to be in support of this.


Solution

  • You don't have to provide a live URL as a type parameter to JsonProvider; you can also provide the filename of a sample file that reflects the structure you expect to see. With that feature, you can do the following steps:

    First, log in to the service and save a JSON file that reflects the API you're going to use.

    Next, do something like the following:

    type TfsData = JsonProvider<"/path/to/sample/file.json">
    let url = "https://example.com/login/etc"
    // Use standard .Net API to log in with your Windows credentials
    // Save the results in a variable `jsonResults`
    let parsedResults = TfsData.Parse(jsonResults)
    printfn "%A" parsedResults.Foo  // At this point, Intellisense should work
    

    This is all very generic, of course, since I don't know precisely what you need to do to log in to your service; presumably you already know how to do that. The key is to retrieve the JSON yourself, then use the .Parse() method of your provided type to parse it.