Fable and Fetch: HTTP Calls in JavaScript Apps With F#

Datetime:2016-08-22 21:59:24          Topic: F#  JavaScript           Share

Fetch provides a generic definition of Request and Response objects (and other things involved with network requests). This will allow them to be used wherever they are needed in the future, whether it’s for service workers, Cache API and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your own responses programmatically. [ project site ]

Dave Thomas created a Fable bindings project called fable-fetch-import . This npm package allows us to use Fetch in JavaScript apps from F#.

Data access

Retrieving data from the web with Fetch is really easy. In the following snippet, we just pull a bit of JSON from an HTTP resource and cast it to a custom type.

open Fable.Import.Fetch
open Fable.Helpers.Fetch

async { 
    try 
        let! records = 
          fetchAs<MyRecord[]>(
              "http://www.server.com/data.json",
              [])
        // ...
    with
    | error -> ...
}

As you can see all JavaScript Promises are already mapped into F#’s async type which makes it really easy to use.

HTTP Post

If you want to post data to an HTTP resource you can do this like in the following sample:

async { 
    let! response = 
      postRecord(
          "http://www.server.com/data.json", 
          myRecord,
          [ RequestProperties.Headers [ 
              HttpRequestHeaders.Accept "application/xml" ]
          ])

    if response.ok then
        match response.Headers.ContentType with
        | None -> // ...
        | Some contentType -> // ...
}

Going Further

If you need to do more complicated calls, then take a look into the Fetch docs . Many of the properties and functions are already available in the Fable bindings. If not please create an issue at the Fable issue tracker and I will try to add it.





About List