How to properly format json to send over using RestClient - ruby-on-rails

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?

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

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.

Related

stub_request must return array in body

I would like test my service with rspec but i got a error in my return body undefined method 'each' for "invoices":String because in my original method i parse an array in the response
I would like know how can i test this method and send a array in return body
My method in service:
def generate_invoices
invoices_ids = []
response = HTTParty.get('https://books.zoho.com/api/v3/invoices?organization_id='\
"#{ENV['ZOHO_ORGANISATION_ID']}&cf_lc_contract_id_startswith=#{#contract_id}&"\
'cf_facture_final=true', headers: { 'Authorization' => "Zoho-oauthtoken #{#access_token}" })
response.code == 200 ? response : raise_error(response.body)
response['invoices'].each do |invoice|
invoices_ids.push invoice['invoice_id']
end
invoices_ids.join(',')
end
stub request i tried:
stub_request(:get, 'https://books.zoho.com/api/v3/invoices?cf_facture_final=true'\
"&cf_lc_contract_id_startswith=123&organization_id=#{ENV['ZOHO_ORGANISATION_ID']}")
.with(headers: { 'Authorization' => 'Zoho-oauthtoken access_token' })
.to_return(status: 200, body: { 'invoices' => [{ "invoice_id": '123' }] }.to_json,
headers: {})
Try this at the end of your call:
.to_return(status: 200, body: '{"invoices" => [{ "invoice_id": "123"}]}', headers: {})

Livebroadcast does not bind to liveStream, how can I bind it?

If I use the following code, I get a valid response (no errors) back from the Youtube API.
Only the stream does not seem to bind.
def bind_broadcast_to_stream(broadcast_id, livestream_id)
data = { empty: "string" }
begin
request = RestClient.post(
"https://www.googleapis.com/youtube/v3/liveBroadcasts/bind?key=#{GOOGLE_API_KEY}&part=id,snippet,contentDetails,status&id=#{broadcast_id}&stream_id=#{livestream_id}",
data.to_json,
content_type: :json,
accept: :json,
authorization: "Bearer #{self.get_token}"
)
return JSON.parse(request)
rescue RestClient::BadRequest => err
return err.response.body
end
end
I can bind it manual by going to the Youtube studio, but then I get a different stream key.
After that (and streaming on of course) I can go live with the following code:
def set_broadcast_status(broadcast_id, status)
data = { empty: "string" }
begin
request = RestClient.post(
"https://www.googleapis.com/youtube/v3/liveBroadcasts/transition?key=#{GOOGLE_API_KEY}&part=id,snippet,contentDetails,status&alt=json&id=#{broadcast_id}&broadcastStatus=#{status}",
data.to_json,
content_type: :json,
accept: :json,
authorization: "Bearer #{self.get_token}"
)
return JSON.parse(request)
rescue RestClient::BadRequest => err
return err.response.body
end
end
It seems I was adding a response body..
According to the Youtube API manual (https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/bind):
Do not provide a request body when calling this method.
def bind_broadcast(broadcast_id, livestream_id)
begin
request = RestClient::Request.execute(
method: :post,
url: "https://www.googleapis.com/youtube/v3/liveBroadcasts/bind",
headers: {
params: { key: GOOGLE_API_KEY, part: "id,snippet,contentDetails,status", id: broadcast_id, streamId: livestream_id, alt: 'json' },
content_type: :json,
accept: :json,
authorization: "Bearer #{self.get_token}"
}
)
return JSON.parse(request)
rescue RestClient::BadRequest => err
return err.response.body
end
end

Error SENDING POST in rails and HTTPPARTY semantic error my request

this is my error when I lanunched my method {"errors"=>{"users"=>["Missing data for required field."]}, "msg"=>"The request was well-formed but was unable to be followed due to semantic errors."}
class BookingNotifier
include HTTParty
def initialize(booking_id)
#booking = Booking.find booking_id
#venue = #booking.event.service.venue
#body = { "users" => [] }
#headers = {
"Accept" => "application/json",
"Authorization" => "ENV_KEY",
"Content-Type" => "application/json"
}
end
def send_venue_notification
venues_objects = []
if #venue.notifications_enabled
venues_objects << { "cellphone" => #booking.event.service.venue.phone,
"country_code" => "+57",
"user_session_keys" => [{ "key" => "Nombre", "value" => #booking.profile.name },
{ "key" => "Centro", "value" => #booking.event.service.venue.name },
{ "key" => "Cupos", "value" => #booking.quantity },
{ "key" => "Horarios", "value" => #booking.time.strftime("%I:%M %p el %d/%m/%Y") }] }.to_json
#body["users"] = venues_objects
make_request_venue
end
end
def make_request_venue
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #header, body: #body)
end
The problem is caused by to_json called in the wrong place.
The whole request body should be sent as a JSON. In your code, you call to_json for a hash that is later pushed into #body["users"] array.
Please remove to_json from send_venue_notification and call it for the #body when sending the request:
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #headers, body: #body.to_json)

How to verify the response from api while writing test with Cucumber

I am working on a Rails project where I have to test the API with Cucumber. I have to test a POST type API and I need to verify its response. I have tried something like:
When(/^I make abc API call$/) do
#url = 'http://example.com/api/abc'
#params = '{
data: {
type: "abc",
attributes: {
title: "example",
all_day: "0",
start_date: "1409175049",
end_date: "1409175049"
}
}
}'
#login_token = 'pHufpGplLTYJnmWh5cqKoA'
end
Then(/^It should return success for abc$/) do
post 'http://example.com/api/abc', body: #params,
headers: { 'Accept' => 'application/json',
'login_token' => #login_token,
'Content-Type' => 'application/json' }
end
But I am not sure how to verify the status code from the response and any attributes from the response. Something like:
Then(/^It should return success for abc$/) do
post 'http://example.com/api/abc', body: #params,
headers: { 'Accept' => 'application/json',
'login_token' => #login_token,
'Content-Type' => 'application/json' }
.to_return(status: 200, body: '{ title: "abc" }')
end
How can I achieve it?
If you are using Capybara this should work for you:
Then /^I should get a response with status (\d+)$/ do |status|
response = post 'http://example.com/api/abc', body: #params,
headers: { 'Accept' => 'application/json',
'login_token' => #login_token,
'Content-Type' => 'application/json' }
response.status_code.should include(status.to_i)
end

NoMethodError in ChatRoomMessagesController

I am doing an AJAX call as the following and trying to parse the JSON recieved in Rails as bellow
AJAX
local_data = {chat:{room_name: chatRoomName ,message: message}}
$.ajax({
type: "POST",
url: '/chat_notify',
dataType: 'json',
async : false,
data: local_data,
success: function(data) {
alert("working");
}
});
Ruby
def notify
#data = ActiveSupport::JSON.decode(params)
#chat_room = ChatRoom.where(:slug => data.chat.name)
#puts #chat_room
puts params.chat
RestClient.post 'https://api.pushbots.com/push/all',
{ "platform" => [0,1] ,
"msg" => "Harsha sent a message." ,
"sound" => "pulse",
"alias" => "harsha#mink7.com",
"badge" => "1",
"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json,
headers = { "x-pushbots-appid" => APP_CONFIG['PUSHBOTS_APPID'],
"x-pushbots-secret" => APP_CONFIG['PUSHBOTS_SECRET'],
:content_type => :json }
render json: true
end
Error
You need to paste your error trace
But I think the problem might in below
puts params.chat
there is no chat method for params , just remove it
or
…………"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json
you need require 'json' to make .to_json available

Resources