Livebroadcast does not bind to liveStream, how can I bind it? - ruby-on-rails

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

Related

How can I use Httparty with rails 6

I am working on a rails application to send a post message to a server but each time i tried to send a post request to the sever there seems to be no post data sent to the server. However, if I use postman to send the message with json format the server responds correctly to the post request. I am relatively new to rails and i am not sure if my configuration is wrong. Please I need help. Here is my my code:
def send_information
HTTParty.post("https://example.com/api/json.php",
:body => {
user: 'Nancy Cole',
item: 'mobile phone',
content: 'Hurray the server has received your message',
id: 2,
:headers => {
'Content-Type' => 'application/json' }
}
)
end
I think you have to change your syntax like below :-
response = HTTParty.post("https://example.com/api/json.php",
headers: {
"Content-Type" => "application/json"
},
body: {user: 'Nancy Cole',
item: 'mobile phone',
content: 'Hurray the server has received your message',
id: 2
}.to_json
)
#syntax
response = HTTParty.post(url,
headers: {},
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

Stubbing a HTTP Party request to run Specs

I need to stub my HTTP Party request to run my spec and I have to store the transaction Id i get from the parsed_response.Here is my stub
stub_request(:post, {MYURL).to_return(status: 200, body: "{'Success': { 'TransactionId' => '123456789' }}", headers: {})
I get my response to the request as
#<HTTParty::Response:0x5d51240 parsed_response="{'Success': { 'TransactionId' => '123456789' }}", #response=#<Net::HTTPOK 200 readbody=true>, #headers={}>
i need to store transactionid from the field
response.parsed_response['Success']["perfiosTransactionId"]
by i am getting null from there.Can any one help me modify my stub response so that i could get the transactionid saved
PS: If I check the fileds of response i get
response.success? ----> true
response.parsed_response --> "{'Success': { 'TransactionId' => '123456789' }}"
response.parsed_response['Success'] ---> "Success"
You're sending the payload in wrong format:
stub_request(
:post,
{MYURL}
).to_return(
status: 200,
body: '{"Success": { "TransactionId": "123456789" }}', # valid json string
headers: {"Content-Type" => "application/json"}
)
It's must be a valid json object, not a ruby hash.
Here is another way:
stub_request(
:post,
{MYURL}
).to_return(
status: 200,
body: {
"Success": { "TransactionId" => "123456789" }
}.to_json, # valid json string
headers: {"Content-Type" => "application/json"}
)

XMLHttpRequest cannot load http://localhost:3000/players/1. Response for preflight has invalid HTTP status code 404

I am building a react-native app with rails api. I have a players_controller with create, index, update actions. I can do all things(create, index, update) from postman. But when I tried form fetch request from react action. I could only index and create player model. On update I get this error in debugger console.
:3000/players/1:1 OPTIONS http://localhost:3000/players/1
XMLHttpRequest cannot load http://localhost:3000/players/1. Response
for preflight has invalid HTTP status code 404
in Rails my players_controller.rb
class PlayersController < ApplicationController
skip_before_action :verify_authenticity_token
respond_to :json
def index
#players = Player.find_by(player_id: params[:player_id])
player = Player.all
render json: #players
end
def create
player = Player.new(player_params)
if player.save
render json: player, status: 201
else
render json: { errors: player.errors }, status: 422
end
end
def update
player = Player.find(params[:id])
player.update(player_params)
if player.save
render json: player, status: 201
else
render json: { errors: player.errors }, status: 422
end
end
private
def player_params
params.require(:player).permit(:username, :profile_pic, :player_id)
end
end
In my react-native app I have action
export const profilePicUpdate = (player, profile) => (dispatch) => {
const obj = player;
obj.profile_pic = profile;
fetch(`http://localhost:3000/players/${player.id}`, {
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
obj
})
}).then(() => {
dispatch({
type: 'PROFILE_PIC_UPDATE',
payload: profile
});
NavigatorService.navigate('Profile');
}).catch((error) => {
console.log('Error', error);
});
};
It is need to see your roues.rb file, but also maybe you need to add
gem 'rack-cors'
and set up it
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
in config/initializers/cors.rb

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?
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.

Resources