Sending form params as body for Guzzle POST request - post

I'm a bit confused about Guzzle's deprecation of sending body parameters, and throwing an exception if $body is an array. The recommended way is seemingly to replace body parameters with form_params.
I'm posting to the eventbrite API here
https://www.eventbrite.com.au/developer/v3/quickstart/
and when doing the following:
$response = $this->guzzleClient->request('POST', $item->eventbriteEndpoint, ['form_params' => $item->parameters]);
It doesn't work (and actually responds like it's received a GET request)
After much trial and error, I discovered I need to json_encode the parameters into a json string and add them into the body like so
$response = $this->guzzleClient->request('POST', $item->eventbriteEndpoint, ['body' => json_encode($item->parameters));
So what is going on here, is form_params the correct replacement for body, and why? Is json_encoding body the correct way to do it, and if so why is form_params mentioned everywhere and this not common knowledge? Something is wrong here, is it
My understanding of form_params and body parameters in a guzzle POST request (most likely)
Guzzle doesn't handle POST requests correctly (unlikely)
The Eventbrite API is not receiving POST requests correctly.
I find guzzle to be incredibly opaque tbh, xdebugging down the rabbit hole usually asks more questions than it answers.
I've actually just discovered something even more bizarre on the Eventbrite end - a POST request to create a new event uses form_params, and updating an event requires the params as json in the body. What.

Related

HTTParty get request ignores query params

I'm trying to make a GET request with a quersytring, however, HTTParty is ignoring my params. For example, I'm doing something like this:
headers = {"User-Agent"=>"whatever", "Authorization"=>"whatever"}
options = {"sport" => "mlb" }
HTTParty.get("https://www.erikberg.com/events.json", query: options, headers: headers)
The response should be empty since yesterday there wasn't any MLB game going on. I checked with curl and worked properly. However, when I use this gem I'm getting NBA games (ignoring the param sport). I asked to the owner of the API and he told me I'm getting two redirects (302, 301).
Any clue of what is failing here? Is my request really using https?
Best regards!

How to decipher ChicagoBoss Post param

I'm a newbie in ChicagoBoss web framework. I have a server which receives a POST request from another server where POST params is of the form:
<<"clientId=STRING_FOR_CLIENT_ID&userId=STRING_FOR_USER_ID&sessionToken=STRING_FOR_SESSION_TOKEN">>
All I have to do is to add clientSecret=CLIENT_SECRET_STRING to this POST params in my server and resend it to the server outside to retrieve access_token.
It would be great if someone suggest some basic code how this can be done.
Are you making the client secret string from the original post data? Anyway, if you can use ibrowse, then:
%% send form data as iolist
Data = <<"clientId=STRING_FOR_CLIENT_ID&userId=STRING_FOR_USER_ID&sessionToken=STRING_FOR_SESSION_TOKEN">>,
ibrowse:send_req("http://httpbin.org/post",
[], post,
[Data, <<"&clientSecret=CLIENT_SECRET_STRING">>]).

Using Webhooks with Rails

I am unfamiliar with Webhooks but I feel like they are the right thing for my app.
I have the following documentation for FluidSurveys webhook
I understand how I can make the webhook through a POST request to their API, but I don't know how can I tell where the webhook is actually going to send the response.
Can I pass any subscription url I want? e.g. https://www.myapp.com/test and is that where webhook will send the data? Also, after the webhook is created I'm not sure how to ensure my Rails app will receive the response that is initiated.
I assume a controller method that corresponds with the url I provide to the webhook.
If I'm correct on the controller handling the webhook, what would that look like?
Any guidance is appreciated.
Webhooks hook into your app via a callback URL you provide. This is just an action in one of your controllers that responds to POST requests and handles the webhook request. Every time something changes to the remote service, the remote service makes a request to the callback URL you provided, hence triggering the action code.
I'll exemplify with the survey created event. You start by defining a callback action for this event, where you handle the request coming from the webhook. As stated here the webhook responds with the following body:
survey_creator_name=&survey_name=MADE+A+NEW+SURVEY&survey_creator_email=timothy#example.com&survey_url=http%3A%2F%2Fexample.com%2Fsurveys%2Fbob%2Fmade-a-new-survey%2F``
Let's leave the headers for now, they don't contain important information. The available body parameters (survey_creator_name, survey_name etc.) will reflect all details regarding the new survey available on the remote service. So let's write a callback action that handles this request:
class HooksController
def survey_created_callback
# If the body contains the survey_name parameter...
if params[:survery_name].present?
# Create a new Survey object based on the received parameters...
survey = Survey.new(:name => params[:survey_name]
survey.url = params[:survey_url]
survey.creator_email = params[:survey_creator_email]
survey.save!
end
# The webhook doesn't require a response but let's make sure
# we don't send anything
render :nothing => true
end
end
Let's add the route for this (in config/routes.rb):
scope '/hooks', :controller => :hooks do
post :survey_created_callback
end
This will enable the POST /hooks/survey_created_callback route.
Now you'll need to subscribe this callback URL to the Webhooks API. First you'll want to know which hooks are available to you. You do this by placing a GET request at /api/v2/webhooks/. In the response you'll find the event name, survey and collector parameters.
Finally, you subscribe to one of the previously listed hooks by placing a request to the POST /api/v2/webhooks/subscribe/ URL with the following contents:
{
"subscription_url": "http://your-absolute-url.com/hooks/survey_created_callback",
"event": "[EVENT NAME FROM THE HOOKS LIST]",
"survey": "[SURVEY FROM THE HOOKS LIST]",
"collector": "[COLLECTOR FROM THE HOOKS LIST]"
}
The response to this will be a code 201 if the hook was created successfully, or code 409, if a webhook for the same callback URL already exists. Or something else, if this went bad :)
You can now test the hook, by creating a survey on the remote service and then watch it getting replicated in your Rails app.
Hope this helps...

Rails impossible to get post response in rack middleware

I made a rails 3 rack middleware to log users actions with request = Rack::Request.new(env).
So i send to my database the request.fullpath and request.user_agent, as detailed below:
My issue appears I want to get the POST response too (to get ids, people name extracted from the JSON payload ...).
So i get the response = Rack::Response.new(request.path). But when i print response.body, i have only my request.path, and the request.params does not contain anything ...
By looking at the response with Firebug, I can see all the data I want.
Thanks for your responses.
Problem resolved !
I finally add status, headers, body = #app.call(env) to my middleware and send the body variable to my service. For each POST request, body contains all the post response I want.

Sending POST requests from Rails controller for authentication

I am quite new to Ruby and RoR, and have been struggling with a problem and am not getting anywhere.
Basically I am building a "proxy" webservice that will handle certain requests, passing them to a third party website. The response received from the third party website is in HTML, which will then be parsed and an appropriate XML response will be given.
I'm at a point where I need to send POST requests via my controller in Rails to authenticate a user, which I'm doing using this code:
require "net/http"
require "uri"
uri = URI.parse("http://myurl.com/members.cgi")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data({"email_login" => "user#email.com", "password_login" => "password"})
response = http.request(request)
My problem lies on the response I am receiving. This specific POST request, when successful (i.e. user has successfully authenticated), is returning a 302 redirect. That in itself is not an issue, as I can follow the redirect by getting the 'location' header value:
redirectLocation = response['location']
Where I'm getting stuck is in keeping myself authenticated when following the redirect with the following line:
redirectResponse = Net::HTTP.get_response(URI.parse(redirectLocation))
This follows the redirect but return a response showing I am not authenticated??
I don't really understanding why this is happening. I can see there is an authentication cookie being returned with my original response by reading:
response['cookie']
So finally my question is what do I need to do to get the server to recognise my authentication status? Pass the cookie with my second request somehow? If so, how do I do it?
Many thanks in advance for your time!
Rog
Yes you need to set the cookie. I think it probably give you some kind of a session id. Which you need to pass with every request.
look at this code snippet for a example on how to pass on a cookie that you get as a response with your new requests.

Resources