Search code examples
ruby-on-railsrubyjsonrest-client

How to properly format json to send over using RestClient


I am trying to implement this javascript code

var token = "<page_access_token>";

function sendTextMessage(sender, text) {
  messageData = {
    text:text
  }
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token:token},
    method: 'POST',
    json: {
      recipient: {id:sender},
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending message: ', error);
    } else if (response.body.error) {
      console.log('Error: ', response.body.error);
    }
  });
}

into ruby on rails code

def reply_back(sender, text)
      page_token = "*****"

      base_uri = "https://graph.facebook.com/v2.6/me/messages"

      messageData = {
        text: text
      }

      qs = {
        access_token: page_token
      }

      json = {
        recipient: {
          id: sender
        },
        message: messageData
      }

      response = RestClient.post base_uri, qs.to_json, json.to_json, :content_type => :json, :accept => :json
      p "this is the response #{response}"

    end

but obviously i am doing something wrong, i am getting this in console

(wrong number of arguments (4 for 2..3))

on line

response = RestClient.post base_uri, qs.to_json, json.to_json, :content_type => :json, :accept => :json

any insight?


Solution

  • You should put all your params in one params hash like this:

      params = {
        recipient: { id: sender },
        message: { text: text },
        access_token: page_token
      }
    
      response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
      p "this is the response #{response}"