Sending an array of string in a request made with rest-client gem

1.5k Views Asked by At

I am creating a gem to implement the Calendly API and I need to make a request like

curl --header "X-TOKEN: <your_token>"
     --data "url=https://blah.foo/bar&events[]=invitee.created"
     https://calendly.com/api/v1/hooks

to create a webhook.

As you may see, events is passed as an array of strings and this is indicated by the [].

I am trying to use RestClient::Request#execute to send this request, but I don't know how to pass this array of strings in this case.

I tried

RestClient::Request.execute(method: :post,
                            url: @uri,
                            params: { url: url,
                                      events: "invitee.#{type}"
                                    },
                            headers: { "X-TOKEN": "#{@api_key}" })

but then I am not sending an array as the API expects.

I also tried

RestClient::Request.execute(method: :post,
                            url: @uri,
                            params: { url: url,
                            'events[]': "invitee.#{type}" },
                            headers: { "X-TOKEN": "#{@api_key}" })

but it didn't work either. I got a bad request error and nothing else.

How should I build my request in this case?

1

There are 1 best solutions below

0
On BEST ANSWER

Posted for visibility (previously answered in comment)

RestClient will appropriately serialize a native ruby Array for you meaning

events: ["invitee.#{type}"]

will be serialized into events[]=invitee.created where type == 'created'. This will work for an Array with multiple values too.

events: ["more","than","one"]

will be converted to events[]=more&events[]=than&events[]=one.

Finally it also handles an other data types inside an Array such as another Hash

events: [{first_name: 'Zaphod', last_name: 'Beeblebrox'}]

will become events[][first_name]=Zaphod&events[][last_name]=Beeblebrox