Skip to content

Instantly share code, notes, and snippets.

Created Mar 15, 2021
What would you like to do?
F# Flurl
#r "nuget: Flurl.Http"
module HttpApi =
open System
open System.Net
open System.Text.Json
open Flurl.Http
type Serializer (opt) =
interface Configuration.ISerializer with
member _.Serialize value = JsonSerializer.Serialize(value, opt)
member _.Deserialize<'T> (json: string) = JsonSerializer.Deserialize<'T>(json, opt)
member _.Deserialize<'T> stream = JsonSerializer.DeserializeAsync<'T>(stream, opt).GetAwaiter().GetResult()
let private defaultSerializer =
let opt = JsonSerializerOptions ()
opt.PropertyNamingPolicy <- JsonNamingPolicy.CamelCase
Serializer opt
type IFlurlRequest with
member request.WithJsonContent () =
request.WithHeader("Content-Type", "application/json")
let configureRequest (url: string) =
url.ConfigureRequest (fun settings ->
//settings.AfterCall <- Action<FlurlCall> logHttpCall
settings.JsonSerializer <- defaultSerializer)
let configureRequestWith serializer (url: string) =
url.ConfigureRequest (fun settings ->
//settings.AfterCall <- Action<FlurlCall> logHttpCall
settings.JsonSerializer <- serializer)
let withTimeout (timeout: TimeSpan) (request: IFlurlRequest) =
request.WithTimeout timeout
let withHeader name (value: string) (request: IFlurlRequest) =
request.WithHeader(name, value)
let allowHttpStatus (httpStatusCodes: HttpStatusCode list) (request: IFlurlRequest) =
request.AllowHttpStatus(Array.ofList httpStatusCodes)
let get (request: IFlurlRequest) =
request.GetAsync() |> Async.AwaitTask
let getJson<'T> (request: IFlurlRequest) =
request.GetJsonAsync<'T>() |> Async.AwaitTask
let getString (request: IFlurlRequest) =
request.GetStringAsync() |> Async.AwaitTask
let getStream (request: IFlurlRequest) =
request.GetStreamAsync() |> Async.AwaitTask
let toJson<'T> (response: IFlurlResponse) =
response.GetJsonAsync<'T>() |> Async.AwaitTask
let postUrlEncoded (input: Map<string, string>) (request: IFlurlRequest) =
request.PostUrlEncodedAsync(input) |> Async.AwaitTask
let postJson<'Input, 'Output> (input: 'Input) (request: IFlurlRequest) =
|> Async.AwaitTask
// sample:
|> HttpApi.configureRequest
|> HttpApi.getJson<{| Data: {| Id: int32; Email: string; Avatar: string |} |}>
|> Async.RunSynchronously
|> printfn "%A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment