ferret icon indicating copy to clipboard operation
ferret copied to clipboard

Post request and conversion to binary type

Open errshoff opened this issue 2 years ago • 3 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

errshoff avatar Jul 25 '22 17:07 errshoff

Hello!

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

Hope it helps, Natalia

Gusyatnikova avatar Jul 25 '22 17:07 Gusyatnikova

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

errshoff avatar Jul 25 '22 18:07 errshoff

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

3timeslazy avatar Aug 10 '22 13:08 3timeslazy

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

errshoff avatar Aug 10 '22 18:08 errshoff

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

leopku avatar Oct 11 '22 08:10 leopku

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 avatar Oct 11 '22 09:10 Gusyatnikova

@Gusyatnikova thanks a lot.

leopku avatar Oct 11 '22 15:10 leopku