Google freebusy api call in rails will not recognizing parameters - ruby-on-rails

I am trying to find all the freebusy times from my primary calendar, but I cannot get the query to recognize my parameters.
In my controller I have:
#freetimes = client.execute(
:api_method => service.freebusy.query,
:parameters => {
'timeMin' => '2013-06-15T17:06:02.000Z',
'timeMax' => '2013-06-29T17:06:02.000Z',
'items' => [{'id' => 'myemail#gmail.com'}]
},
:headers => {'Content-Type' => 'application/json'})
the response I get is:
--- !ruby/object:Google::APIClient::Schema::Calendar::V3::FreeBusyResponse
data:
error:
errors:
- domain: global
reason: required
message: Missing timeMin parameter.
code: 400
message: Missing timeMin parameter.
However is shows that it took the parameters, but they did not get attached to the query:
--- !ruby/object:Google::APIClient::Result
request: !ruby/object:Google::APIClient::Request
parameters:
timeMin: '2013-06-15T17:06:02.000Z'
timeMax: '2013-06-29T17:06:02.000Z'
items:
- id: myemail#gmail.com
Any help solving this would be greatly appreciated!

solved this by specifying the request body
client.execute(
:api_method => service.freebusy.query,
:body => JSON.dump({
:timeMin => ,
:timeMax => ,
:items =>
}),
:headers => {'Content-Type' => 'application/json'})

I was having a similar problem. An alternative, is that you can build a FreeBusyRequest object.
Like this:
body = Google::Apis::CalendarV3::FreeBusyRequest.new
body.items = [calendar_id]
body.time_min = "2016-06-29T13:00:00z"
body.time_max = "2016-06-29T21:00:00z"
body
```
and then you can pass it into a CalendarService object like this:
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
service.query_freebusy(body)
this will definitely return a status 200 response with a body.

Related

How can I increase timeout for HTTParty post method in rails?

I have a method in rails to send post requests to a third party API. The code looks similar to the following:
data = HTTParty.post("url",
:headers=> {'Content-Type' => 'application/json'},
:body=> { update => true, first_name => "name" }
)
With this, after exactly one minute, the process is terminated with the following error.
<Net::HTTPGatewayTimeOut 504 GATEWAY_TIMEOUT readbody=true>
Set the default by:
module HTTParty
default_timeout your_preferred_timeout
end
or set it individually by:
data = HTTParty.post("url",
headers: {"Content-Type" => "application/json"},
body: {update => true, first_name => "name"},
timeout: your_preferred_timeout
)
you can try
data = HTTParty.post("url",
headers: {"Content-Type" => "application/json"},
body: {update => true, first_name => "name"},
open_timeout: 0.5,
write_timeout:1,
read_timeout:3
)
also you can reference
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#attribute-i-write_timeout

How to send header and cookies with rest-client gem

In Code I am trying to send both the header and cookies in same request
below is the code
#result = RestClient.post(
'url',
{:billingSourceCode => "code"},
{:cookies => {:session_id => "1234"}},
{:headers => {'Content-Type' =>'application/json',
"Authorization" => "key",
"Accept" => "application/json"}})
i am getting below error message
ArgumentError (wrong number of arguments (4 for 3)):
Cookies are part of headers. Here in RestClient :
#cookies = #headers.delete(:cookies) || args[:cookies] || {}
See in initialize method in https://github.com/rest-client/rest-client/blob/master/lib/restclient/request.rb
Do this -
#result = RestClient.post(
'url',
{:billingSourceCode => "code"},
{:headers => {'Content-Type' =>'application/json',
"Authorization" => "key",
"Accept" => "application/json"},
{:cookies => {:session_id => "1234"}}
})
Try
RestClient::Request.execute(
method: :post,
url: 'whatever',
cookies: {:session_id => "1234"},
headers: {'Content-Type' =>'application/json',
"Authorization" => "key",
"Accept" => "application/json"})

Post to an API using OAuth

I'm trying to post to an API. The API takes files and converts them to JSON
Here is what I am doing:
consumer = OAuth::Consumer.new(consumer_key,secret, :site => uri)
accesstoken = OAuth::AccessToken.new(consumer, core_access_token, core_access_secret)
params = {:body => {
:binaryData => data,
:extension => "txt",
:locale => 'en_gb',
:instanceType => 'xray',
:fieldList => {"field" => ["All"]}
}.to_json,
:headers => {
'Accept' => 'application/json',
'Content-Type' => 'application/json' ,
}
}
result = accesstoken.post(action, params)
And I get back the response:
<Net::HTTPBadRequest 400 Bad Request readbody=true>
What does this error mean? Wrong URI? Wrong access tokens? or Incorrect usage of the OAUTH Gem (ie, my code is wrong)
I think it should be like this:
consumer = OAuth::Consumer.new(consumer_key,secret, :site => uri)
accesstoken = OAuth::AccessToken.new(consumer, core_access_token, core_access_secret)
headers => {
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
result = accesstoken.post(action, data, headers)

Send array in JSON POST request with HTTParty

I'm trying to work with a 3rd party API that requires an array to be sent within a POST request body. I've already gotten the hang of sending JSON; I've read you just need to set some headers and call to_json on the POST body. However, I'm not sure how to embed an array within that POST body. I've tried the following:
HTTParty.post(url,
:body => {
:things => [{:id => 1}, {:id => 2}, {:id => 3}],
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
)
but this is giving me a server error, leading me to believe the array isn't being formatted correctly. Could someone please advise on how to send an array within a JSON POST request? Thanks!
EDIT:
The error I get back is the following:
#<HTTParty::Response:0x10 parsed_response=nil,
#response=#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>,
#headers={"error_message"=>["Can not deserialize instance of java.lang.Long out of
START_OBJECT token at [Source: org.apache.catalina.connector.CoyoteInputStream#30edd11c;
line: 1, column: 15] (through reference chain: REDACTED[\"things\"])"],
"error_code"=>["0"], "content-length"=>["0"],
"date"=>["Wed, 13 Aug 2014 22:53:49 GMT"], "connection"=>["close"]}>
The JSON should be in the format:
{ "things" : [ {"id": "..."}, {"id: "..."}, ... ] }
The simplest way to embed an array within a POST body using HTTParty in Ruby on Rails is to pass the request to an instance variable (any name of your choice can suffice for the instance variable).
So we will have
#mypost = HTTParty.post(url,
:body => {
:things => {
:id => 1,
:id => 2,
:id => 3
},
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'xxxxxxxxxx'
'Accept' => 'application/json'
})
Here is an example of an HTTParty Post Request
#myrequest = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
:body => {
:books => {
:name => "#{#book.name}",
:author => "#{#book.author}",
:description => "#{#book.description}",
:category_id => "#{#book.category_id}",
:sub_category_id => "#{#book.sub_category_id}"
},
}.to_json,
:headers => { 'Content-Type' => 'application/json',
'Authorization' => '77d22458349303990334xxxxxxxxxx',
'Accept' => 'application/json'})
That's all
I hope this helps.
I had a similar requirement for a SurveyMonkey API, the below will create a params_hash with nested array of hashes
create the fields array of hashes
fields = []
i =0
while i < 10 do
fields << {":id#{i}" => "some value #{i}"}
i += 1
end
method with optional splat field variable
def get_response(survey_id, respondent_ids, *fields )
params_hash = {}
params_hash[:survey_id] = "#{survey_id}"
params_hash[:respondent_ids] = respondent_ids
params_hash[:fields] = fields
#result = HTTParty.post("http://"some.address.here",
#:debug_output => $stdout,
:headers => {'Authorization' => "bearer #{#access_token.to_s}", 'Content-type' => 'application/json'},
:body => params_hash.to_json,
)
end

Constantly get Authentication+failed.+API+credentials+are+incorrect

I'm trying to create simple PayPal Pay API operation, when I run this code from console it gave me response, that payment is created.
Now, when I'm tring to run it from my controller it gives me
Authentication+failed.+API+credentials+are+incorrect.
Here is my controller :
def pay
require 'httpclient'
require 'xmlsimple'
clnt = HTTPClient.new
credentials = {
'USER' => 'payer_1342623102_biz_api1.gmail.com',
'PWD' => '1342623141',
'SIGNATURE' => 'Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL '
}
header = {"X-PAYPAL-SECURITY-USERID" => "payer_1342623102_biz_api1.gmail.com",
"X-PAYPAL-SECURITY-PASSWORD" => "1342623141",
"X-PAYPAL-SECURITY-SIGNATURE" => "Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL ",
"X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "XML",
"X-PAYPAL-APPLICATION-ID" => "APP-80W284485P519543T"
}
data = {"actionType" => "PAY",
"receiverList.receiver(0).email"=> "denmed_1342605975_biz#gmail.com",
"receiverList.receiver(0).amount" => "10",
"currencyCode" => "USD",
"cancelUrl" => "http://127.0.0.1:3000",
"returnUrl" => "http://127.0.0.1:3000",
"requestEnvelope.errorLanguage" => "en_US"}
uri = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"
res = clnt.post(uri, data, header)
#xml = XmlSimple.xml_in(res.content)
payKey = #xml["payKey"].to_s()
payKey = payKey.tr("[]", "")
payKey = payKey[1..20]
redirect_to "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay?cmd=_ap-payment&paykey=#{payKey}"
end
Is everything ok ? Can anyone suggest reason my request fails ?
One good man found my error. I redirect user to the wrong url.
This line:
redirect_to "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay?cmd=_ap-payment&paykey=#{payKey}"
Should be:
redirect_to "https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=#{paykey}"
I got the same error: I realized I forgot to include
sandbox_email_address: xxx#example.com
in my yml file

Resources