#Simple Example binding the dog API?

1 messages · Page 1 of 1 (latest)

fierce field
#

I'd like to bind the dogapi in F#. But I'm having trouble converting my C# example into an Fsharp example. I don't know what to do about GetFromJsonAsync<List<Dog>>. Normally this takes a List<Dog>> class that looks like this

public class Dog
{

    public string Id { get; set; }

    public string Url { get; set; }

    public int Width { get; set; }

    public int Height { get; set; }
}

But I'm not sure I can do this in F#? I'm also getting errors like

0>Program.fs(27,1): Warning FS0020 : The result of this expression has type 'Async<'a>' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'.

So I might be going down the wrong path using my C# code as a base. Does anyone know the best way to do this in F#?

open System
open System.Net.Http
open System.Net.Http.Headers
open System.Net.Http.Json
open System.Text
open System.Text.Json

let private baseUrl = "https://api.thedogapi.com/v1/"
let mutable private httpClient: HttpClient option = None

let initializeHttpClient (apiKey: string) =
    let client = new HttpClient(BaseAddress = Uri(baseUrl))
    client.DefaultRequestHeaders.Accept.Clear()
    client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue("application/json"))
    client.DefaultRequestHeaders.Authorization <- AuthenticationHeaderValue("X-API-Key", apiKey)
    httpClient <- Some client
    
let getRandomDogAsync (client : HttpClient option) : Async<Dog> = async {
    match client with
    | Some client ->
        let! dog = client.GetFromJsonAsync<List<Dog>>("images/search") |> Async.AwaitTask
        dog[-1]
    | None ->
        failwith "HttpClient not initialized. Call initializeHttpClient first."
}

initializeHttpClient "MyAPIKey" |> getRandomDogAsync |> Async.AwaitTask
warm oxide
#

You need to replace the Async.AwaitTask on the last line with Async.RunSynchronously. I wouldn't pass an option of HttpClient into getRandomDogAsync if it needs one to work properly. The initializeHttpClient returns unit which is why you are getting the error message. Get rid of the mutable HttpClient and return the client from the function. You Dog class can be a simple record type. Have fun!