Question

I have to implement the curl POST request below listed, in Ruby, using Rest-Client.

I have to:

  • send params in header;
  • send params (that do not contain a file) as multipart/form-data:

    $ curl -X POST -i -H "Authorization: Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001" \
        https://api.somewhere.com/endpoint -F sku_id=608399
    

How can I translate the curl request using the RestClient rubygem?

Reading documentation (multipart paragraph): https://github.com/rest-client/rest-client I coded as:

@access_token = 2687787877876666686b213e92aa3ec7e1afeeb560000000001
url = 'https://api.somewhere.com/endpoint'
req = { authorization: "Bearer #{@access_token}"}


RestClient.post url, req, {:sku_id => 608399, :multipart => true}

But I get a server error; is the Ruby code above correct?

Thanks a lot, Giorgio

Was it helpful?

Solution 2

It's code not valid for RestClient implementation. headers should follow after payload.

module RestClient 
 def self.post(url, payload, headers={}, &block)
  ...
 end
end

UPDATE

@access_token should be a string "2687787877876666686b213e92aa3ec7e1afeeb560000000001"

then

RestClient.log = 'stdout'
RestClient.post url, {:sku_id => 608399, :multipart => true}, req

and log

RestClient.post "https://api.somewhere.com/endpoint", "--330686\r\nContent-Disposition: form-data; name=\"sku_id\"\r\n\r\n608399\r\n--330686--\r\n", "Accept"=>"*/*; q=0.5, application/xml", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001", "Content-Length"=>"79", "Content-Type"=>"multipart/form-data; boundary=330686"

OTHER TIPS

Since I had trouble understanding the example Dmitry showed, here is an example for creating a Multipart request to upload an image:

response = RestClient.post 'https://yourhost.com/endpoint',

{:u_id => 123, :file => File.new('User/you/D/cat.png', 'rb'), :multipart => true},

{:auth_token => xyz5twblah, :cookies => {'_cookie_session_name' => cookie}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top