How can I use Httparty with rails 6 - ruby-on-rails

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
)

Related

Livebroadcast does not bind to liveStream, how can I bind it?

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

HTTParty POST call returning invalid JSON

I am looking to post to an API with my email address, but I cannot get a workable response. When I simply cURL the API in the terminal, the data is returned as expected.
#omnics2 = HTTParty.post('https://qo.api.liveramp.com/v1/idl_resolution',
:headers => {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'X-Api-Key' => 'my api key',
'Accept-Encoding' => 'gzip, deflate',
'Content-Length' => '59148'
},
:body => {'email' => 'me#email.com'}
)
The above returns this error
<HTTParty::Response:0x7ff5b0d49ab0 parsed_response="Invalid JSON in request: invalid character 'e' looking for beginning of value\n", #response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, #headers={"content-type"=>["text/plain; charset=utf-8"], "x-content-type-options"=>["nosniff"], "date"=>["Fri, 02 Aug 2019 21:41:58 GMT"], "content-length"=>["78"], "via"=>["1.1 google"], "alt-svc"=>["clear"], "connection"=>["close"]}>
I can wrap the entire call with a .to_json method, which allows for a succesful call, I just can't do anything with the response using the standard #omnics.body method. When I wrap everything in a .to_json method, this is the result I get:
=> "{\"content-type\":[\"text/plain; charset=utf-8\"],\"x-content-type-options\":[\"nosniff\"],\"date\":[\"Fri, 02 Aug 2019 21:45:32 GMT\"],\"content-length\":[\"78\"],\"via\":[\"1.1 google\"],\"alt-svc\":[\"clear\"],\"connection\":[\"close\"]}"
I've tried adding to_json methods to the header section and body sections, as recommended here like so:
:body => {'email' => 'me#email.com'}.to_json instead of wrapping the entire function, but that also errors out.
Would love any thoughts here as I am merely a hobbiest developer and am probably overlooking something obvious.
Finally got this to work. I had to make the body values enclosed within an array. Here's the syntax:
#omnics3 = HTTParty.post("https://qo.api.liveramp.com/v1/idl_resolution", options)
options = {
headers: {
"Content-Type": "application/json",
"X-Api-Key" => "my api key"
},
:debug_output => STDOUT,
query: { data: true },
body: [
{ email: ["anemail#address.com"] },
{ email: ["joe#gmail.com"] },
].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"}
)

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

Resources