Trouble to make a request with httparty - ruby

I'm using rest-client to make some request in a API, inside my automation scenarios with cucumber.
I'm trying to change the gem to Httparty but I can not do it.
url_login = "https://mu.com/login"
header = {'Content-Type': 'application/json'}
payload =
{
"username": "cpd141",
"password": "****",
"agentSign": "ASS"
}.to_json
rest-client gem
response = RestClient::Request.execute(method: :post, url: url_login, payload: payload, headers: header)
response - <RestClient::Response 200 "{\"id\":\"1436...">
httparty gem
response = HTTParty.post(url_login,headers: header, body: payload)
response = {"errorMessage"=>"RequestId: 04377c34-709b-41f3-a379-65615fca2681 Process exited before completing request"}

Related

Users_not_found in HTTParty request to SlackAPI when curl works

I'm trying to use GET request using httparty gem to have info about specific user from SlackAPI. From curl it works well
curl --data "token=SLACK_TOKEN&email=user#example.com" https://slack.com/api/users.lookupByEmail
But my code below seems to be broken because I received an error {"ok":false,"error":"users_not_found"}
module Slack
class GetUserId
def call
response = HTTParty.get("https://slack.com/api/users.lookupByEmail", payload: payload, headers: headers)
end
def headers
{
'Content-Type' => 'application/json',
'Authorization' => 'Bearer SLACK_TOKEN'
}
end
def payload
{
email: "user#example.com"
}.to_json
end
end
end
If you check their documentation, it seems that API do not accept JSON-form but rather "application/x-www-form-urlencoded.
So something like:
headers: {
'Authorization' => 'Bearer SLACK_TOKEN,
"Content-Type" => "application/x-www-form-urlencoded"
},
body: {
"token=SLACK_TOKEN”,
”email=user#example.com"
...
Reference: https://api.slack.com/methods/users.lookupByEmail

RestClient post request in ruby on rails

RestClient post request
I tried post request couple ways
#user = {name: 'xxxxxx', email: 'xxxxxx#gmail.com', password: 'qwertyqqq'}
RestClient.post 'http://localhost:4123/api/users?token=<token>', #user
RestClient::Request.execute(method: :post, url: 'http://localhost:4123/api/v1/users', token: '<token>', payload: '#user', headers: {"Content-Type" => "application/json"})
Error: RestClient::BadRequest: 400 Bad Request or RestClient::UnprocessableEntity: 422 Unprocessable Entity
Success cases
When i made a get request with rest client and with curl is just fine.
RestClient.get 'http://localhost:4123/api/v1/users?token=<token>'
With curl:
Get request:
curl -X GET http://localhost:4123/api/v1/users/1?token=<token>
Post request for helpy:
curl -d '{"name":"xxxx","email":"xxxx#gmail.com","password":"12345678", "admin": true, "role":"admin"}' -H "Content-Type: application/json" -X POST http://localhost:4123/api/v1/users?token=<token>
The difference between the CURL version and the RestClient version is that in the CURL version you send a JSON string as payload but in the RestClient sends the string '#user'.
It should be fine when you actually send JSON:
RestClient.post(
"http://localhost:4123/api/v1/users?token=<token>",
#user.to_json,
{ content_type: :json, accept: :json }
)

Payload in Typhoeus Ruby Delete Request

I am trying to send request payload(like in a post call) with Typhoeus Delete call.
As far as I know, The latest update to the HTTP 1.1 specification (RFC 7231) explicitly permits an entity body in a DELETE request:
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
I tried this code, but body/payload is not retrievable
query_body = {:bodyHash => body}
request = Typhoeus::Request.new(
url,
body: JSON.dump(query_body),
method: :delete,
ssl_verifypeer: false,
ssl_verifyhost: 0,
verbose: true,
)
request.run
response = request.response
http_status = response.code
response.total_time
response.headers
result = JSON.parse(response.body)
At the other side, It comes in an encoded way, where I can not retrieve it
Other side code is like :
def destroy
respond_to do |format|
format.json do
body_hash = params[:bodyHash]
#do stuff
render json: {msg: 'User Successfully Logged out', status: 200}, status: :ok
end
format.all {render json: {msg: 'Only JSON types are supported', status: 406}.to_json, status: :ok}
end
end
Let me cite the specification:
A payload within a DELETE request message has no defined semantics;
sending a payload body on a DELETE request might cause some existing
implementations to reject the request.
I would NOT say it can be called as explicit permission to send payload with DELETE request. It tells you MAY send a payload, but the processing of such a request remains entirely at the discretion of the server.
And this is what happens:
At the other side, it comes in an encoded way, where I can not retrieve it
Why can't you send your payload as a part of POST request, which is guaranteed to be processed by the server normally?
I finally looked at all my requests in which I was payload (POST and PUT) and observed that I was not sending headers along with this DELETE request.
It looks something like this:
query_body = {:bodyHash => body}
request = Typhoeus::Request.new(
url,
body: JSON.dump(query_body),
method: :delete,
ssl_verifypeer: false,
ssl_verifyhost: 0,
verbose: true,
headers: {'X-Requested-With' => 'XMLHttpRequest', 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json, text/javascript, */*', 'enctype' => 'application/json'}
)
request.run
response = request.response
http_status = response.code
response.total_time
response.headers
result = JSON.parse(response.body)
Just adding headers to it, made it work

Ruby Typhoeus gem - Invalid Json in body?

I have the following code:
require 'Typhoeus'
url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/",
userpwd: "username_test:password_test",
method: :post,
body: {
'subscription_url' => 'http://glacial-spire-test.herokuapp.com/hooks/response_created_callback',
'event' => 'response_complete'
},
headers: { 'Content-Type' => "application/json"})
response = url.run.body
puts response
This returns a response code of 400 and an error:
Content-Type set to application/json but could not decode valid JSON in request body.
Here are the docs for the API call I am making: http://docs.fluidsurveys.com/api/webhooks.html
POST /api/v2/webhooks/subscribe/¶
Returns a status of 409 if a webhook with the subscription url already exists. Returns a
status of 201 if the webhook was successfully created. Requests must be sent as an
application/json-encoded dictionary with the required fields subscription_url and event
Sample request (ACCORDING TO DOCS):
{
"subscription_url": "http://fluidsurveys.com/api/v2/callback/",
"event": "response_complete",
"survey": 1,
"collector": 1
}
What am I doing wrong here? survey and collector are optional params, and I don't see an issue with the json in my body.
I am guessing you might need to convert the request body into JSON using a library like Oj (https://github.com/ohler55/oj). Using the Oj library:
requestBody = {
'subscription_url' => 'http://glacial-spire-test.herokuapp.com/hook/response_created_callback',
'event' => 'response_complete'
}
url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/",
userpwd: "username_test:password_test",
method: :post,
body: Oj.dump(requestBody, mode: :compat),
headers: { 'Content-Type' => "application/json"})
response = url.run.body
puts response
The critical line is:
body: Oj.dump(requestBody, mode: :compat)
If you need to load any JSON content to Ruby, just use Oj.load

Api Requests with Ruby gem Typhoeus

What is wrong with the following request?
request = Typhoeus::Request.new("http://fluidsurveys.com/api/v2/groups",
method: :get,
userpwd: "test_user:test_password",
headers: { 'ContentType' => "application/json"})
response = request.body
puts response
This returns undefined method body for #<Typhoeus::Request:0x007f8e50d3b1d0> (NoMethodError)
The following request works fine with httparty:
call= "/api/v2/groups/"
auth = {:username => "test_user", :password => "test_password"}
url = HTTParty.get("http://fluidsurveys.com/api/v2/groups",
:basic_auth => auth,
:headers => { 'ContentType' => 'application/json' } )
response = url.body
puts response
EDIT:
I tried this:
response = request.response
puts response.body
with no luck. I receive this : undefined method body for nil:NilClass (NoMethodError)
From https://github.com/typhoeus/typhoeus
You need to do the get before the response body is available.
EDIT: Here is an operable solution. It doesn't use your website, which I couldn't access even manually. But, this returns response code 200 and the response_body. Running this in my debugger showed the complete response, which you could see using "puts response.inspect".
class TyphoeusTry
require 'typhoeus'
request = Typhoeus::Request.new("http://www.google.com",
method: :get,
userpwd: "test_user:test_password",
headers: { ContentType: "application/json"})
response = request.run
puts response.response_body
end
The problem is that you didn't actually execute your request. The following code should work.
request = Typhoeus::Request.new("http://fluidsurveys.com/api/v2/groups",
method: :get,
userpwd: "test_user:test_password",
headers: { 'ContentType' => "application/json"})
request.run
response = request.response
response_code = response.code
response_body = response.body

Resources