0

I'm running a simple Sinatra app where I need to query some data and send a POST via JSON to a webhook URL for processing. I'm not sure how to properly format the records I've retrieved for HTTParty.

The contacts are printing to /account/{account_id}/contacts.json how I want them, they data just isn't being sent successfully.

app.rb

get "/account/:account_id/contacts.json" do
  @contacts = Contact.where("sfid = ?", params[:account_id])
  HTTParty.post("https://hooks.webapp.com/hooks/catch/387409/1us4j3/",
  { 
    :body => [ @contacts ].to_json,
    :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
  })
  @contacts.to_json
end
csakon
  • 581
  • 2
  • 6
  • 23
  • First of all, there is a difference in how data is being printed `@contacts.to_json` and how they are send `[ @contacts ].to_json`. It can be the problem. But if it's not, we need more information about how are you sure it's not being sent. – André Guimarães Sakata Apr 03 '17 at 22:32
  • 'where' already returns an array to variable `@contacts` . So type of `@contacts` is already an array. I don't think there is need to convert to array again before converting to json. `:body => @contacts.to_json` is okay. – Mayank Apr 04 '17 at 14:48
  • @AndréGuimarãesSakata I'm sure it's not being send because I have a test route that sends HTTParty.post("https://hooks.webapp.com/hooks/catch/387409/1us4j3/", { :body => [ {:name => 'value1', :privacy => 'value2'} ].to_json, :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'} }) successfully and is caught by the webhook. The code I posted in my question does not get caught. – csakon Apr 04 '17 at 15:13
  • @Mayank I attempted at/contacts.to_json as you suggested and was presented with an internal server error and these logs - https://www.evernote.com/shard/s2/sh/60c2d37d-df78-43d9-ac1d-0dacc4f926eb/a74b9a1cb7b17950dcbdaf7f92dec470 – csakon Apr 04 '17 at 15:14

1 Answers1

1

It seems the error is

2.3.1/lib/ruby/2.3.0/net/http/generic_request.rb:183:in `send_request_with_body'

It does not found any body in your request. You are sending the parameters body and head inside a hash.

Try this:

get "/account/:account_id/contacts.json" do
  @contacts = Contact.where("sfid = ?", params[:account_id])
  HTTParty.post("https://hooks.webapp.com/hooks/catch/387409/1us4j3/",
    :body =>  @contacts.to_json,
    :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
  )
  @contacts.to_json
end

You can checkout this post also for any more information regarding HTTP post Here

Hope this helps..

Community
  • 1
  • 1
Mayank
  • 727
  • 6
  • 9