F#- How can we validate the whole schema of API response using HttpFs.Client or Hopac?

152 views Asked by At

I have a test where after getting a response I would like to validate the entire schema of the response (not individual response node/value comparison).

Sample test:

    [<Test>]
        
let howtoValidateSchema () =
            
    let request = Request.createUrl Post "https://reqres.in/api/users"
                       
               |> Request.setHeader (Accept "application/json")
                       
               |> Request.bodyString """{"name": "morpheus",
         "job": "leader"}"""
         
               |> Request.responseAsString
                       
               |> run

Is there a way that I can save my expected Schema somewhere and once I get the response I do the comparison to check that response has same number of nodes (neither less nor more than expected schema)?

I am ok to opt for other libs like FSharp.Data if we there is no direct way in HttpFs.Client. I looked at FSharp.Data (https://fsharp.github.io/FSharp.Data/library/JsonProvider.html) but not able to seek how it meets the requirements where the schema comparison needs to be done with the savedExpectedSchemaJson=ResponseJson.

1

There are 1 answers

1
Koenig Lear On BEST ANSWER

You can use Newtonsoft.Json.Schemato validate schemas:

open Newtonsoft.Json.Schema
open Newtonsoft.Json.Linq

let schema = JSchema.Parse expectedSchema
let json = JObject.Parse responeJson
let valid = json.IsValid schema

However this assumes you have a schema predefined somewhere. If you don't have such schema is best to use the JsonProvider who can infer it for you.

Run the call manually and save the result in a sample.json file and create a type using the JsonProvider:

type ResponseSchema = JsonProvider<"sample.json">

and you can use this type to parse any new content based on the sample (provided that the sample is a representative.

ResponseSchema.parse response

This won't validate the schema but will try to meet as best as it can given the input.