TheSharperDev

Educating about C# and F#

Examples Using HttpClient in F#

 Photo by Luca Bravo on Unsplash

I like F#! It’s got a lot of useful features that helps me write better software.

At times I have a harder time finding documentation and examples. There’s just not as many people using and blogging about it as C#.

This week I was using some F# and had trouble finding examples of using HttpClient in F#. So I decided to fix that problem and blog about it.

Correct HttpClient Usage is Not Simple

Before talking about HttpClient and F#, it’s important to call out that using HttpClient correctly is not simple.

Here are two articles that I’ve read multiple times and still don’t understand all the details.

The underlying problem is that even though HttpClient implements IDisposable it doesn’t get disposed. So creating a new HttpClient for every request can quickly lead to resource starvation if you have high load.

I haven’t used HttpClient enough in F# to recommend best practices, but avoid creating a new HttpClient for every request.

That being said, lets dive into some examples.

Test API

I first created a Test API using Giraffe to respond to a GET and POST request.

It fakes the creation of a User, then fakes the retrieving of a User.

Fairly simple stuff.

HttpClient Examples

Then in my F# Console app, I create a User to match what the Test API will return.

The following performs a Get request:

While the following performs a Post request:

Then wire that all up to run each function.

(Check the git repo for a full example)

A couple things to mention:

  • The Async.AwaitTask transforms the task into F# async type. If you’re using a library like Giraffe to build a web app, using tasks all the way would be a better option.
  • I’m creating the HttpClient one time and reusing across both methods. Aim for reusing HttpClients.
  • In PostAsync, I’m returning a Result type. Which is a functional way to deal with the ambiguity on whether the http request completed successfully or not.

Final Thoughts

I hope anyone who uses the HttpClient in F# finds this article a good starting point. As I continue learning F# I’ll continue blogging about the things that I’m learning.

Git Repo