DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez • Edited

This is an F# script that posts a Post like object to the json placeholder API and deserializes the json response to a Post.

you can copy into a file and run it like this:

  • dotnet fsi ./filename.fsx
#r "nuget: FsHttp" // specify the http library

// open the required namespaces
open FsHttp
open FsHttp.DslCE
open System.Text.Json

// define the shape of the data
// these are known as Records in F#
type Post =
    { userId: int
      id: int
      title: string
      body: string }

// In F# records can't have null values for most types
// so we use an anonymous record (`{| |}` instead of `{}`)
// because we don't have an id value yet
let payload =
    JsonSerializer.Serialize(
        {| userId = 1
           title = "Sample"
           body = "Content" |}
    )

let response =
    // declare the request
    http {
        POST "https://jsonplaceholder.typicode.com/posts"
        body
        json payload
    }
    // send the request, it can also be done asynchronously
    |> Request.send
    // get the stream back (rather than downloading the response in bytes/string
    |> Response.toStream
    // deserialize it using .NET base class library classes like JsonSerializer
    |> JsonSerializer.Deserialize<Post>

// you can now check the response in the console
printfn "%A" response
Enter fullscreen mode Exit fullscreen mode