Search code examples
ruby-on-railsrubyruby-on-rails-4curlrest-client

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?


Solution

  • 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"}
                               )