Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume HttpClient from F#?

I'm new to F# and stuck in understanding async in F# from the perspective of a C# developer. Say having the following snippet in C#:

var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();

How to write the same in F#?

like image 996
abatishchev Avatar asked Oct 04 '14 17:10

abatishchev


Video Answer


1 Answers

Just my two cents. But my understanding is that we should be handling the HttpRequestException when using EnsureSuccessStatusCode().

Below is the start of a module wrapping HttpClient that will buffer the response of a URL into a string and safely wrap in a Result<'a, 'b> for improved fault tolerance.

module Http =
    open System    
    open System.Net.Http

    let getStringAsync url =
        async {
            let httpClient = new HttpClient() 
            // This can be easily be made into a HttpClientFactory.Create() call
            // if you're using >= netcore2.1

            try 
                use! resp = httpClient.GetAsync(Uri(url), HttpCompletionOption.ResponseHeadersRead) |> Async.AwaitTask                       
                resp.EnsureSuccessStatusCode |> ignore

                let! str = resp.Content.ReadAsStringAsync() |> Async.AwaitTask
                return Ok str
            with
            | :? HttpRequestException as ex -> return ex.Message |> Error
        }
like image 176
pim Avatar answered Sep 26 '22 10:09

pim