Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data in a post request with RestClient

I'm trying to mimic a curl request using the RestClient Ruby gem, and so far, I've been having a lot of trouble trying to send in a payload. My curl request looks something like this

curl URL -X POST -u API_KEY -d '{"param_1": "1"}'

I've been trying to replicate this with RestClient using something like this:

RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: {"param_1" => "1"})

Alas, I keep getting 400 - Bad Requests errors when doing this. Am I sending data over the wrong way? Should I be using something other than payload?

like image 782
rboling Avatar asked Oct 25 '15 01:10

rboling


2 Answers

Change:

payload: {"param_1" => "1"})

To:

payload: '{"param_1": "1"})'

Also, specify the headers.

So, it becomes:

RestClient::Request.execute(method: :post,
                            url: 'your_url',
                            user: 'API_KEY',
                            payload: '{"param_1": "1"}',
                            headers: {"Content-Type" => "application/json"}
                           )
like image 87
K M Rakibul Islam Avatar answered Nov 15 '22 00:11

K M Rakibul Islam


Just Change:

payload: {"param_1" => "1"}

To:

payload: {"param_1" => "1"}.to_json

So, then it becomes:

RestClient::Request.execute(method: :post,
                            url: 'your_url',
                            user: 'API_KEY',
                            payload: {"param_1" => "1"}.to_json,
                            headers: {"Content-Type" => "application/json"}
                           )
like image 21
Irfan Ahmad Avatar answered Nov 14 '22 22:11

Irfan Ahmad