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
Related
I have try to making a POST request to google cloud messaging server as follow from my Rails controller using httparty gem
#response = HTTParty.post("https://android.googleapis.com/gcm/notification",
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
)
#json = JSON.parse(#response.body)
render :json => #json
The response I got it not a notification key. It is
{
"error": "BadJsonFormat"
}
What's wrong in my code?
My Rails controller request format is
POST /api/fcm HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: cfd40d1e-81f4-5402-a3cd-f6749f868291
{
"user_id" : "42"
}
I guess httparty gem expects json data
So replace
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
with
:body => {
:text => {
:operation => "remove",
:notification_key_name => "43",
:registration_ids => [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
Try removing to to_json on post. This would work if you were calling it for a Hash, but what it's doing here is double-escaping your string (which is already valid JSON).
If you want to send a minimal JSON request (i.e. without the extra spaces and carriage returns), you can also use
JSON.parse('{
"operation" : "remove",
...
}').to_json
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"})
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)
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
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.