Petros Kyriakou
Petros Kyriakou

Reputation: 5343

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?

Upvotes: 2

Views: 1789

Answers (2)

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

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}"

Upvotes: 4

Ilya
Ilya

Reputation: 13487

According to documentation, you should merge you params and pass it in method as one object:

params = qs.merge(json)
response = RestClient.post(base_uri,
                           params.to_json,
                           content_type: :json, accept: :json)

This method expects 2 or 3 arguments. In this case the third argument is a hash { content_type: :json, accept: :json }. Since it is a last argument, you can omit curly braces.

Upvotes: 3

Related Questions