How to send header and cookies with rest-client gem - ruby-on-rails

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

Related

FCM API Bad Request

I'm trying to push a notification through FCM from my Ruby on Rails project, here is my code:
require 'net/http'
require 'json'
def send_notifications
log = Logger.new("log/notifications.log")
begin
uri = URI.parse("https://fcm.googleapis.com/fcm/send")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
key = '...'
hash = {:notification => {:sound => "default", :title => "test", :text => "test", :badge => "0"}, :data => {:targetID => "1", :to => "..."}}
req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json', 'Authorization' => "key=#{key}"})
req.body = hash.to_json
response = http.request(req)
log.debug("response #{response.body}")
rescue => e
log.debug("failed #{e}")
end
end
I'm getting Bad Request 400 error, and debugging the response body only shows this: "to"
Please help me debug this issue. Thank you

Making POST Request to GCM server for notification key fails from Rails Controller

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

Instagram API - Unable to request access token

Using HTTParty I tried to request for the access token as below:
result = HTTParty.post("https://api.instagram.com/oauth/access_token",
{
:body => [ { "client_id" => xxxxxxxxxx, "client_secret" => xxxxxxxxxxxxx,
"grant_type" => "authorization_code",
"redirect_url" => 'http://localhost:4000/access_token', "code" => xxxxxxxx } ].to_json,
:headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
})
But the response says that #400, "error_type"=>"OAuthException", "error_message"=>"You must provide a client_id"}, #response=#, #headers={"content-language"=>["en"], "expires"=>["Sat, 01 Jan 2000 00:00:00 GMT"],........
Can't figure out why.. Help!
You can change content-type into:
'Content-Type' => 'application/x-www-form-urlencoded'
For more information click instagram-api-authentication-must-provide-client-id
I hope this help you.

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

Resources