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
Related
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
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
I' am trying to create a simple wrapper for skyscanner API. The problems is that when try to get the sessionKey, what I get is <HTTParty::Response:0x10 parsed_response=nil, #response=#<Net::HTTPUnsupportedMediaType 415 Unsupported Media Type readbody=true>. I am not sure what is that I am doing wrong. I am new to rails and I will appreciate any direction on how to solve this problem?. Thanks
require 'httparty'
class Skyscanner
include HTTParty
format :json
base_uri "http://partners.api.skyscanner.net/apiservices/pricing"
def self.find(originplace, destinationplace)
#options = { query:
{
:apiKey => "API_KEY",
:country => "US",
:currency => "USD",
:locale => "en-us",
:adults => 1,
:children => 0,
:infants => 0,
:originplace => originplacea,
:destinationplace => destinationplace,
:outbounddate => "2017-02-20",
:inbounddate => "2017-02-27",
:locationschema => "iata",
:cabinclass => "Economy"
}
}
#headers = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'}
#sessionkey_request = HTTParty.post("http://partners.api.skyscanner.net/apiservices/pricing/v1.0/",:body => #options,:headers => #headers)
puts #sessionkey_request.inspect
#get_sessionkey = #sessionkey_request.headers['location']
#sessionkey = #get_sessionkey.to_s().split('/').last
puts #sessionkey.inspect
end
end
If anyone have a better way of approaching this wrapper, please advice me on how to. Thanks
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 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.