Skip to content

Instantly share code, notes, and snippets.

@akhansari
Created March 15, 2021 14:54
Show Gist options
  • Save akhansari/96c67d6abf943ed616dd4ba89f9c47b0 to your computer and use it in GitHub Desktop.
Save akhansari/96c67d6abf943ed616dd4ba89f9c47b0 to your computer and use it in GitHub Desktop.
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) =
request
.WithJsonContent()
.PostJsonAsync(input)
.ReceiveJson<'Output>()
|> Async.AwaitTask
// sample:
"https://reqres.in/api/users/1"
|> 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