Today’s post is really light, and nothing too involved. It is composed mostly of notes and examples using the fluent http client Flurl with F#.
If you’re looking for an alternative to the HttpClient, Flurl offers some nice functionality and ergonomics. For reference I’m using version 3.2.4 of the client.
1
dotnet add package flurl.http --version 3.2.4
Before getting into examples, there is some small setup. I’ve defined a User type to send and receive data. Based on the Flurl response objects (which you’ll see in a moment) I have some response types specifically for HTTP GET and POST. Note here, I’m only including the args, since that is all I care about, but this could also include things like data or headers as well. For simplicity, I’m using httpbin.org, which echos what I send.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
open System open System.IO open Flurl open Flurl.Http
A simple HTTP GET is straight-forward. Here I am returning the raw result, so you can see the general structure of the data returned. Query parameters are sent using the SetQueryParams method. GetStringAsync returns the raw string result.
It is nice to see the raw result, but it is much more practical to deserialize the response into the desired object. To do this, change the Get call to GetJsonAsync<GetResult>.
Performing an HTTP POST is similar to a GET. In this case use the PostJsonAsync method along with the object to serialize. Like the previous example, ReceiveJson<PostResult> will deserialize the response into the desired object.
Up until now, it has been send/receiving json payloads. But Flurl can be used to download files as well. Here I how a pdf can be downloaded and saved using DownloadFileAsync.