Search code examples
ruby-on-railsrubyapiwebhooksrails-api

How to handle Trello webhooks? RoR API


I am new at backend developing (RoR). Sorry for my English.

Now I am working with Trello API and trying to receive (handle) webhooks. I'm using ruby-trello gem. Also I'm using ngrok.

I successfully created webhooks (in Trello). Now when I edit Trello object (marked by webhook), I have the request from Trello to my app to WebhooksController#receive.

routes.rb:

  post '/webhooks' => 'webhooks#receive', :defaults => { :format => 'json' }
  get '/webhooks' => 'webhooks#complete', :defaults => { :format => 'json' }

webhooks_controller.rb

class WebhooksController < ApplicationController

  skip_before_action :verify_authenticity_token

  @@data = File.read('public/data.json')

  def complete
    render status: 200
  end

  def receive
    JSON.parse(request.body.read)
    render :json => @@data
  end

end

But all the time I see JSON::ParserError (765: unexpected token at ''):

Now I just want to see webhooks request's json for understanding and code next steps.

Can anyone help please? Thank you in advance. :)


Solution

  • You can log what is coming from webhook request's JSON using logger.info.

    For example:

    def receive
      logger.info "Trello webhook request's JSON: #{params}"
      # rest of your code...
    end
    

    Then you have to check your logs. Probably it will be in log/production.log.

    If you are able to make Trello hit your local server, you can debug your action to see what is in the webhook request's JSON putting a debugger statement in the action.

    For example:

    def receive
      debugger
      JSON.parse(request.body.read)
      render :json => @@data
    end
    

    Also, request.body.read is not the best way to get your params. You can just call params and it will return a Hash with your params. Actually, request.body.read does not return an object in a valid format to be parsed to JSON, I think that is the cause of the exception.