DEV Community

Rob Mulpeter
Rob Mulpeter

Posted on • Edited 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

Newtonsoft.Json/13.0.1
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 =
    JsonConvert.DeserializeObject<Post>(response)

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

    task {        
        try
            let! response = client.SendAsync(message, ct)
            if response.StatusCode = HttpStatusCode.OK then
                let! payload = response.Content.ReadAsStringAsync()
                return Some (DeserializePost payload)
            else
                return None
        with
        | :? 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 =    
    //GET
    task {
        let client = new HttpClient()
        let tokenSource = new CancellationTokenSource(3000)
        let token = tokenSource.Token      
        let getMessage = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts/1")

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

main.Wait()
Enter fullscreen mode Exit fullscreen mode

Output

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)