POST JSON to API using Rails and HTTParty - ruby-on-rails

I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
#cfg = 'xxxsupport'
#user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
#api_key = 'MrUser411'
#project = 'excelm-manoke'
#url_new_string = 'https://api.squishlist.com/auth/?cfg='+#cfg+'&user_key='+#user_key+'&api_key='+#api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by #url_new_string
response = HTTParty.get(#url_new_string.to_str) #submit the string to get the token
#parsed_and_a_hash = JSON.parse(response)
#token = #parsed_and_a_hash["token"]
#make a new string with the token
#urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+#cfg+'&token='+#token+'&method=squish.issue.submit&prj='+#project
#submit and get a result
#result = HTTParty.post(#urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
And then I have a page that I go to to see the result of the controllers actions and it has the following code.
<p><%= #result %></p>
I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?
I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.

I solved this by adding .to_json and some heading information
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}

Related

Creating "shell object" to submit form params via Change.org API

I am using the change-ruby gem to take form params and submit them via the Change.org API. I am new to Rails and so I am likely not fully understanding how to properly implement this library and use it in my controller.
I have a form that posts some params to the #sign action in ChangeController. In this controller I attempt to include the change-ruby gem, as well as its resources.
Currently, though, when I submit the form I am given the error: uninitialized constant Petitions::ChangeController::Petition on the line where I attempt to create a new Petition object (petition = Petition.new(client)). What am I missing?
To be clear, my app uses Engines and this one happens to be called Petitions.
ChangeController code:
# Visit https://github.com/ericisaiah/change-ruby for documentation
require 'change-ruby'
module Petitions
include Change::Resources
class ChangeController < ApplicationController
def sign
client = Change::Requests::Client.new({ :api_key => ENV["CHANGE_API_KEY"], :secret_token => ENV["CHANGE_SECRET"] })
# Get the petition (this is where the error occurs)
petition = Petition.new(client)
# Get the petition id from the Petition URL
petition_id = petition.get_id(params[:petition_url][:value])
# Load the petition
petition.load(petition_id)
# Get the petition auth key
petition.request_auth_key({
:requester_email => params[:requester_email][:value],
:source => params[:page_slug][:value],
:source_description => "Campaign page that is gathering signatures to help the petition."
})
# Submit signature
petition.signatures.add_signature({
:email => params[:sig_email],
:first_name => params[:sig_first],
:last_name => params[:sig_last],
:address => params[:sig_street],
:city => params[:sig_city],
:state_province => params[:sig_state],
:postal_code => params[:sig_zip],
:country_code => params[:sig_country],
:hidden => params[:sig_hidden]
})
end
end
end
Answer was simple: the include Change::Resources line needed to be inside the ChangeController class, otherwise it wasn't accessible to the controller.

Google + moments not visible on user's feed using google_api_client gem

I am trying to post to user's stream using google api client, I am using below mentioned code
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
client = Google::APIClient.new
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.access_token = USER_ACCESS_TOKEN
plus = client.discovered_api('plus', 'v1')
moment = {
:type => 'http://schemas.google.com/AddActivity',
:target => { :id => Time.now.to_i.to_s,
:description => 'well this is it',
:name => 'Well this is it'
}
}
req_opts = { :api_method => plus.moments.insert,
:parameters => { :collection => 'vault', :userId => 'me', },
:body_object => moment
}
response = client.execute!(req_opts).body
After executing the above code I am getting the response as follow
{"kind"=>"plus#moment",
"type"=>"http://schemas.google.com/AddActivity",
"target"=>{"kind"=>"plus#itemScope", "id"=>"1422863753", "description"=>"well this is it", "name"=>"Well this is it"}}
But when I go to user's profile then I am not able to see this activity anywhere in profile.
Note: The moment methods do not write directly to a user's Google+ stream. They instead write to a user's profile, and are not necessarily viewable by others depending on the user's preferred sharing settings.
Manage app activities in Google
To find where moments are visible, view the profile about page and look for the "Apps with Google+ Sign-in" section.

How to make a post request with httparty [duplicate]

I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
#cfg = 'xxxsupport'
#user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
#api_key = 'MrUser411'
#project = 'excelm-manoke'
#url_new_string = 'https://api.squishlist.com/auth/?cfg='+#cfg+'&user_key='+#user_key+'&api_key='+#api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by #url_new_string
response = HTTParty.get(#url_new_string.to_str) #submit the string to get the token
#parsed_and_a_hash = JSON.parse(response)
#token = #parsed_and_a_hash["token"]
#make a new string with the token
#urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+#cfg+'&token='+#token+'&method=squish.issue.submit&prj='+#project
#submit and get a result
#result = HTTParty.post(#urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
And then I have a page that I go to to see the result of the controllers actions and it has the following code.
<p><%= #result %></p>
I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?
I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.
I solved this by adding .to_json and some heading information
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}

TinyMCE Spellcheck expected JSON Response in Rails

I am using TinyMCE and I have rolled my own spellchecker using FFI-Hunspell.
I am just rendering this hardcoded response but when I click the spell check button in the WYSIWYG editor, it says that there aren't any misspelled words.
render :json => {:id => "#{params[:id]}", :result => {"presents" => ["presnts"], "motor" => ["moors"]}}.to_json
So, what is the JSON supposed to look like?
I am using the tinymce_rails gem. I would have thought it was using the newer version. Anyways, I found this link that describes in detail how the request/response should look: https://github.com/spohlenz/tinymce-rails. Effectively, the response for the older version of tinyMCE is this:
render :json => ({:id => nil, :result => ['badk', 'wirds'], :error => nil}).to_json
Also, it actually uses a second request to get the suggestions. And those should look like:
render :json => ({:id => nil, :result => ['bad', 'bed'], :error => nil}).to_json

Check username availability using jquery and Ajax in rails

I am using rails with jquery and ajax to check the availability of username. I am using
the following plugin for jquery validation purpose.
https://github.com/posabsolute/jQuery-Validation-Engine
In my controller i am using the following method to check the username availability.
def check_name
name = params[:name]
if name.strip == ""
render :json => { :available => false }
return
end
user = User.find(:first, :conditions => [ "name = ?", name])
if user
render :json => ["name", false , "This name is already taken"]
else
render :json => ["name", true , ""]
end
end
Is this the correct way to write the method? I checked many of the username availability
posts in this forum, but nothing worked out.
I am adding the answer. Sorry for the delay guys.
First credit to the plugin:https://github.com/posabsolute/jQuery-Validation-Engine .
Used the plugin for validations in the application.
In the view, i had
<%= f.username_field :username, :id => 'free-user', :placeholder=>'User Name', :class => "validate[required, ajax[ajaxUserCall]]", "data-prompt-position" => "topLeft:0,9"%>
In the same view, in java script:
<script type="text/javascript">
$(document).ready(function(){
$("#free-user").bind("jqv.field.result", function(event, field, errorFound, prompText){
if(errorFound){
$(".continue").attr("disabled", false); // .continue is a button
} else{
$(".continue").attr("disabled", true);
}
})
});
</script>
In routes.rb i have the following route.
match '/check-user' =>"users#check_user" // creating route for ajax call
In jquery.validationEngine-en.js file i have following:
"ajaxUserCall": {
"url": "/check-user",
// you may want to pass extra data on the ajax call
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
In users controller, i have the following method
def check_user
user = params[:fieldValue]
user = User.where("username = ?", username).first
if user.present?
render :json => ["free-user", false , "This User is already taken"]
else
render :json => ["free-user", true , ""]
end
end
To check the Username/Email Availability do the following:
Using the https://github.com/posabsolute/jQuery-Validation-Engine
edit the validationsEngines-en.js file for the AJAX calls, one for the email will look like the following:
"ajaxEmailAvailable": {
"url": "/route_to_send_the_parameters",
// you may want to pass extra data on the ajax call
"alertTextOk": "* This email is available",
"alertText": "* This email is already taken",
"alertTextLoad": "* Validating, please wait"
},
Make sure you configure your routes.rb file to match the route you want to use, the default action with the call is a GET HTTP Request.
Next set up the proper action in your controller to handle the request (I included a helper in the Application Controller so that the input value can be sanitized before queried in the database:
CONTROLLER HANDLING THE REQUEST
def username_availability
scrubb = help.sanitize(params[:fieldValue], :tags => '')
user = User.find_by_email(scrubb)
if user.blank?
render :json => ["INPUT_ID", true , ""]
else
render :json => ["INPUT_ID", false , "This email is already taken"]
end
end
If you are unsure of the proper INPUT ID, watch the server logs for the parameters passed during the call and do a simple copy-paste. By default the request passes the INPUT ID and INPUT VALUE.
To gain access to this helper add the following:
APPLICATION CONTROLLER
def help
Helper.instance
end
class Helper
include Singleton
include ActionView::Helpers::TextHelper
end
Now on the form itself, your input should read as the following:
<%= c.text_field :email, "data-validation-engine"=>"validate[required, custom[email], ajax[ajaxEmailAvailable]]" %>
As per the proper functionality always place the AJAX call as the last validation.
Don't forget to include jquery.js, jquery.validationEngine-en.js, jquery.validationEngine.js and validationEngine.jquery.css in the head of the document [in that order of js] and to call a
<script type="text/javascript">$(function() {$("#FORM_ID").validationEngine();});</script>
If you want to do this for username, just edit the above appropriately.

Resources