DEV Community

Rob Mulpeter
Rob Mulpeter

Posted on • Updated on

F# Http Request

The purpose of this article is to give you an example of making a HTTP request in F# wrapped in a try-catch with a cancellation token.

The example was built in a console application using .NET 6 and requires the below packages

Enter fullscreen mode Exit fullscreen mode

It also makes use of the free to use API placeholder service JSONPlaceholder.

Paste the below code into your Program.fs and execute.

open System
open System.Net
open System.Net.Http
open System.Threading
open System.Threading.Tasks
open Newtonsoft.Json

type Post =
    { userId: int
      id: int
      title: string
      body: string }

let DeserializePost (response: string) : Post =

let GetItem
    (client: HttpClient)
    (message: HttpRequestMessage)
    (ct: CancellationToken) : Task<option<Post>> =    

    task {        
            let! response = client.SendAsync(message, ct)
            if response.StatusCode = HttpStatusCode.OK then
                let! payload = response.Content.ReadAsStringAsync()
                return Some (DeserializePost payload)
                return None
        | :? TaskCanceledException as ex -> printfn $"Task Canceled Exception: {ex.Message}"
                                            return None
        | :? TimeoutException as ex -> printfn $"Timeout Exception: {ex.Message}"
                                       return None
        | ex -> printfn $"General Exception: {ex.Message}"
                return None

let main =    
    task {
        let client = new HttpClient()
        let tokenSource = new CancellationTokenSource(3000)
        let token = tokenSource.Token      
        let getMessage = new HttpRequestMessage(HttpMethod.Get, "")

        let! item = GetItem client getMessage token
        printfn $"{item}"

Enter fullscreen mode Exit fullscreen mode


Some({ userId = 1
  id = 1
  title =
   "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
  body =
   "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto" })
Enter fullscreen mode Exit fullscreen mode

Further Readings

Making F# HTTP calls using either System.Net.Http, Http.Fs or Flurl -> here
Configuring Serilog into F# -> Here

Top comments (0)