Search code examples
jsonrubysinatrahttpartyzapier

Sending JSON Webhook Response


I'm trying to receive a request from a webservice via JSON and send a successful response message back if the token is correct along with some other identifying information, otherwise send a proper error message

post "/hook/foo/bar" do
puts request.env

if request.env['TOKEN'] === "secret_code"
  HTTParty.post("https://hook.com/hooks/catch/foo/bar/",
  {
    :body => @info.to_json,
    :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
  })

  [200, {}, "Success"]
else
  [400, {}, "Authorization Failed"]
end

The service sending the hook (Zapier) says it sends successfully, but i'm not responding any meaningful data to them that I can use. I believe my formatting for my responses is wrong, but i'm not sure how.


Solution

  • David from the Zapier Platform team here.

    Per the sinatra docs, you can return:

    An Array with three elements: [status (Fixnum), headers (Hash), response body (responds to #each)]

    So you're sending back no hints on the content type and a string as the body. This is valid, and your hook succeeds, but you can do better!

    Zapier parses the response from an outgoing hook as JSON, so it's best to send that back.

    I've just tested the following example:

    require 'sinatra'
    require 'json'
    
    get '/' do
      'hello world!'
    end
    
    post '/hook' do
      {message: 'great!'}.to_json
    end
    

    and my response was parsed! enter image description here

    If you want to set a status code, honestly the easiest way to do it is with the function status(400) anytime before your return. That being said, a 401 is probably the code you want for Unauthorized", rather than400`. Either way though, zapier will flag that run as an error.

    ​Let me know if you've got any other questions!