Ruby: POST data to a url - ruby-on-rails

In a rails app I want to be able to post some information to another website inside a method without visiting the website. I'm fairly new to the topic so act as if I’m 5 years old.
My idea so far:
def create_button
button = {
:name => 'test',
:type => 'buy_now',
:callback_url => 'http://www.example.com/my_custom_button_callback',
:description => 'sample description',
:include_email => true
}
"https://thesite.com/api/v1" + button.to_query
# post logic here
end

Ruby ships with the Net::HTTP library for making HTTP requests. There are a lot of gems that wrap HTTP as well, my favorite is Faraday. Look into those libraries, it is pretty straightforward how to make a POST request with them.

There are a lots of gems that do this for free but if you only want to use the standard library, try something like this:
require "net/http"
require 'net/https'
require "uri"
uri = URI.parse("https://thesite.com/api/v1")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
# I'm unsure if symbols will work
button = {
"name" => 'test',
"type" => 'buy_now',
"callback_url" => 'http://www.example.com/my_custom_button_callback',
"description" => 'sample description',
"include_email" => true
}
req.set_form_data(button)
res = https.request(req)

Try: Net::HTTP
uri = URI.parse("https://thesite.com/api/v1")
button = {
:name => 'test',
:type => 'buy_now',
:callback_url => 'http://www.example.com/my_custom_button_callback',
:description => 'sample description',
:include_email => true
}
res = Net::HTTP.post_form(uri,button)
res.code
res.body # response from api

Related

Jira: Add new Released Version via API

We're trying to automate this task in our release process so that our scripts add a new released version in Jira. It will then iterate through a list of jira issues that have 'shipped' in this release and tag them with the Release Version we just added.
I can't seem to find any examples of adding a new Released Version in Jira [Project > Releases] via REST API.
Can you please share how you are handling this?
Add new Released Version via Jira API code snippet using ruby with httparty.
require 'httparty'
def self.create_version(version)
create_version_url = "https://jira2.server.com/rest/api/2/version"
#result = HTTParty.post(create_version_url,
:basic_auth => {:username => 'user', :password => 'password'},
:body => { :description => '',
:name => version,
:archived => false,
:released => true,
#:releaseDate => "2016-07-06",
:userReleaseDate => "6/Jul/2017",
:project => "project_name",
:projectId => "10102"
}.to_json,
:headers => { 'Content-Type' => 'application/json' })
puts #result
end
Set Fixed Version of jira issue:
def self.set_issue_fixedVersion(ticket,fixedVersion)
edit_issue_url = "https://jira2.<server>.com/rest/api/2/issue/#{ticket}"
#result = HTTParty.put(edit_issue_url,
:basic_auth => {:username => 'user', :password => 'password'},
:body => { "fields" => { "fixVersions"=> [{"name" => #{fixedVersion}}]}}.to_json,
:headers => { 'Content-Type' => 'application/json' })
puts #result
end
Could be something like this:
Create the new version: POST /version
You will also have to specify the project that the version belongs to
This will also make the version show up on the Project -> Releases page
Search for fixed issues, so you have their issue keys: POST /search
Possibly you can also get this list in another way, ie. from your version control system
Update the fixVersion of those issues with your new version: /PUT issue/{issueIdOrKey}
Release your version: PUT /version/{id}
In the body of your request specify the releaseDate and set released to true

updating a column Parse Rest API

i am trying to update a Users information for ex. Phone, email etc.
i looked at this: https://parse.com/docs/rest/guide#users-updating-users
so i wrote this in my controller:
#response = HTTParty.put('https://api.parse.com/1/users/',
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token],
"Content-Type" => "application/json"},
:data => {"phoneNumber" => "9994432"})
I return #response in a view and get back this:
{"error"=>"requested resource was not found"}
I was thinking maybe its because im not passing the user's objectid in the url?
Well, now that you have played with creating HTTP requests to API manually, it's time to switch to some library/gem for interactions with Parse. Hopefully, people who built the library that you will find, already have dealt with many routine tasks (like formatting your JSON properly – the error you are investigating right now), and have good documentation for many cases.
I suggest parse-ruby-client.
Add gem 'parse-ruby-client', github: 'adelevie/parse-ruby-client' to Gemfile (it's better to use master version, not the current Rubygems version, because they are saying that there are some useful changes which are not yet pushed to Rubygems), then run bundle install as usual, and you are good to go.
Object saving is as easy as
game_score = client.object("GameScore")
game_score["score"] = 1337
game_score["playerName"] = "Sean Plott"
game_score["cheatMode"] = false
result = game_score.save
puts result
according to their documentation.
UPD. Answering original question. You can use a function to provide object id dynamically:
def update_user(object_id)
#response = HTTParty.put("https://api.parse.com/1/users/#{object_id}",
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token],
"Content-Type" => "application/json"},
:data => {"phoneNumber" => "9994432"})
end
My solution is force the variables to int and string
response = HTTParty.put("https://api.parse.com/1/users/#{object_id}",
:headers => {
"X-Parse-Application-Id" => ENV['PARSE_APP_ID'].to_s,
"X-Parse-REST-API-Key" => ENV['PARSE_API_KEY'].to_s,
"X-Parse-Session-Token" => token.to_s,
"Content-Type" => "application/json"},
:body => {"h_optimum" => optimum.to_i,
"h_moderate" => moderate.to_i,
"h_appalling" => appalling.to_i}
)

Using Ruby Webrick HTTPAuth with LDAP

The app I am writing has the ability to have a login popup appear and it authenticates against a hard coded username/password constant pair. I would like to authenticate against our central LDAP server. the we dont have a base however we do have a bind_dn string of "cn=USERFOO,ou=it,o=corporate". The variables user/pass are passed in through the basic login box.
I am trying to do this through ActiveLdap however I dont mind using any other library as long as I can validate the credentials through a single sign on against our LDAP server using the HTTPAuth since is written completely in Webrick Ruby. Below is a sample of the function I am calling.
Does anyone have any idea how to do this?
Thanks in advance.
def authenticate_ldap(req,res)
authlabel = "LDAP Authentication"
HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
ActiveLdap::Base.setup_connection(
:host => 'ldap.internalserver.com',
:port => 389,
:bind_dn => "cn=#{user},ou=it,o=corporate",
:password_block => Proc.new { pass },
)
}
return
end
I figured out a solution. The person who manages our LDAP server provided the incorrect ldap connection string, but even with that it still didn't work.
The solution I discovered that did indeed make a connection with very basic validation is something to this effect for anyone else interested in a very simple ldap authentication popup in pure Ruby.
def authenticate(req,res)
authlabel = 'LDAP Authentication'
HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
if pass.to_s != ''
ldap = Net::LDAP.new
ldap.host = "ldap.serverfoo.com"
ldap.port = 389
result = ldap.bind_as(
:base => "t=basetreefoo",
:filter => "uid=#{user}",
:password => pass
)
if result
ldap = Net::LDAP.new :host => "ldap.serverfoo.com",
:port => "389",
:auth => {
:method => :simple,
:username => "",
:password => ""
}
group_name = Net::LDAP::Filter.eq("cn", "#{user}")
group_type = Net::LDAP::Filter.eq("groupmembership", "cn=infra,ou=IT,o=Corporate")
filter = group_name & group_type
treebase = "t=basetreefoo"
ldap.search(:base => treebase, :filter => filter) do |entry|
if entry.dn.to_s != ""
puts 'success'
return
end
end
end
end
puts 'fail'
}
end

Changing Content-Type to JSON using HTTParty

I am trying to use Ruby on Rails to communicate with the Salesforce API. I can fetch data easily enough but I am having problems posting data to the server. I am using HTTParty as per Quinton Wall's post here:
https://github.com/quintonwall/omniauth-rails3-forcedotcom/wiki/Build-Mobile-Apps-in-the-Cloud-with-Omniauth,-Httparty-and-Force.com
but all I seem to be able to get from the salesforce server is the error that I am submitting the body as html
{"message"=>"MediaType of 'application/x-www-form-urlencoded' is not supported by this resource", "errorCode"=>"UNSUPPORTED_MEDIA_TYPE"}
the responsible code looks like:
require 'rubygems'
require 'httparty'
class Accounts
include HTTParty
format :json
...[set headers and root_url etc]
def self.save
Accounts.set_headers
response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json))
end
end
anyone have an idea why the body should be being posted as html and how to change this so that it definitely goes as json so that salesforce doesn't reject it?
Any help would be appreciated. cheers
The Content-Type header needs to be set to "application/json". This can be done by inserting :headers => {'Content-Type' => 'application/json'} as a parameter to post, ie:
response = post(Accounts.root_url+"/sobjects/Account/",
:body => {:name => "graham"}.to_json,
:headers => {'Content-Type' => 'application/json'} )
You have to set the Content-Type header to application/json. I haven't used HTTParty, but it looks like you have to do something like
response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json) , :options => { :headers => { 'Content-Type' => 'application/json' } } )
I'm somewhat surpised that the format option doesn't do this automatically.

Integration testing Rails API with basic authentication

I'm trying to get a test signing in using basic authentication. I've tried a few approaches. See code below for a list of failed attempts and code. Is there anything obvious I'm doing wrong. Thanks
class ClientApiTest < ActionController::IntegrationTest
fixtures :all
test "adding an entry" do
# No access to #request
##request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("someone#somemail.com:qwerty123")
# Not sure why this didn't work
#session["warden.user.user.key"] = [User, 1]
# This didn't work either
# url = URI.parse("http://localhost.co.uk/diary/people/1/entries.xml")
# req = Net::HTTP::Post.new(url.path)
# req.basic_auth 'someone#somemail.com', 'qwerty123'
post "/diary/people/1/entries.xml", {:diary_entry => {
:drink_product_id => 4,
:drink_amount_id => 1,
:quantity => 3
},
}
puts response.body
assert_response 200
end
end
It looks like you might be running rails3 -- Rails3 switched over to Rack::test so the syntax is different. You pass in an environment hash to set your request variables like headers.
Try something like:
path = "/diary/people/1/entries.xml"
params = {:diary_entry => {
:drink_product_id => 4,
:drink_amount_id => 1,
:quantity => 3}
env=Hash.new
env["CONTENT_TYPE"] = "application/json"
env["ACCEPT"] = "application/json"
env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("someone#somemail.com:qwerty123")
get(end_point, params, env)
This could work too, but it might be a sinatra only thing:
get '/protected', {}, {'HTTP_AUTHORIZATION' => encode_credentials('go', 'away')}
Sinatra test credit
This works for me in Rails 3
#request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials('username', 'password')
get :index

Resources