3

I have a RoR application from where I need to call a 3rd party API with several different calls. GET requests work fine with both Postman and HTTParty, but I can't get POST to work with latter. In Postman, I have a default request with basic auth, headers and a half dozen parameters in the body with the default form-data option.

The Postman request works fine, but I've been having hard time to replicate the request to HTTParty, leading to the API responding with error as parameters are missing.

Here's some of the code I've been working with to no avail:

options = { headers: {"Accept"=>"application/json", "Content-Type"=>"application/json"}, 
:debug_output => $stdout, body: { "param1" => 1, "param2" => 5, 
"param3" => 'foo', "param4" => 'bar', "param5" => 'test' }
.to_json, 
basic_auth: {:username=>'censored', :password=>'censored'} }

response = HTTParty.post("#{Settings.api_url}", options)

opening connection to ...
opened
starting SSL for ...
SSL established
<- "POST ... HTTP/1.1\r\nAccept: application/json\r\n
Content-Type: application/json\r\nAuthorization: Basic censored\r\nConnection: close\r\n
Host: www.censored.com\r\n
Content-Length: 113\r\n\r\n"
<- "{\"param1\":1,\"param2\":5,\"param3\":\"foo\",\"param4\":\"bar\",\"param5\":\"test\"}"
-> "HTTP/1.1 200 OK\r\n"
-> "Server: Apache\r\n"
-> "Set-Cookie: PHPSESSID=...; path=/\r\n"
-> "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
-> "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
-> "Pragma: no-cache\r\n"
-> "Content-Length: 61\r\n"
-> "Connection: close\r\n"
-> "Content-Type: application/json\r\n"
-> "\r\n"
reading 61 bytes...

and then comes the error response. I tried with various combinations regarding body, also trying to set Accept and Content-Type headers to multipart/formdata but didn't get it working. How could I replicate the Postman request?

bmes
  • 61
  • 2
  • 8
  • 2
    `HTTParty#post` is just a thin wrapper around `Net::HTTP::Post` from the stdlib. If you really want to post formdata use `Net::HTTP.post_form` which will encode the body for you. – max Sep 23 '19 at 11:52
  • Thanks! This solved my problem and the request is now sent in correct form to the API in question. – bmes Sep 24 '19 at 06:34

0 Answers0