MontFerret/ferret

Post request and conversion to binary type

errshoff opened this issue · 7 comments

Hi all!
I need to send a POST request from my script. This is example code:

LET req = {hello: "world"}
LET result = IO::NET::HTTP::POST({
	url: "https://httpbin.org/post",
	body: JSON_STRINGIFY(req),
	headers: {"Content-Type": "application/json"}
})

RETURN JSON_PARSE(TO_STRING(result))

But when:
$ ferret exec post.fql

I get the following error:
invalid type: expected [binary], but got string: .body: IO::NET::HTTP::POST({url:"https://httpbin.org/post",body:JSON_STRINGIFY(req),headers:{"Content-Type":"application/json"}}) at 3:13

And that's right...
But how do I convert string to binary?
I did not find such a function in the documentation

Hello!

You can use to_binary function:
Let binaryBody = to_binary('"id"=15')

Hope it helps,
Natalia

Does not work:
compile query: not found: function: 'TO_BINARY'

@errshoff didn't you try to pass req instead of JSON_STRINGIFY(req)?

@3timeslazy I tried. The result is the same:
invalid type: expected [binary], but got object

Same issue. not found: function: 'TO_BINARY'
@errshoff , should you plz sharing how did you fixed it?

Hi, @leopku, you can try to add by yourself something like this:

  1. To pkg/stdlib/types file to_binary.go with function
func ToBinary(ctx context.Context, args ...core.Value) (core.Value, error) {
	err := core.ValidateArgs(args, 1, 1)

	if err != nil {
		return values.None, err
	}

	val := args[0].String()

	return values.NewBinary([]byte(val)), nil
}
  1. To pkg/stdlib/types/tib.go add raw to RegisterLib func
    "TO_BINARY": ToBinary,

  2. In your script use
    `Let binaryBody = to_binary('"id"=15')
    LET result = IO::NET::HTTP::POST({

    url: "https://httpbin.org/post",

    body: binaryBody,

    headers: {"Content-Type": "application/json"}

})
`

The reason of this error is absence of to_binary in ferret

@Gusyatnikova thanks a lot.