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}
)
Related
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
I've incorporated viewpoint gem to send emails using Microsoft exchange services. I don't have any issues of sending plain html email. I am not able to send a email with document attached. Someone please help me in this.
please find the sample below
endpoint = "http:///.asmx"
ep_user = ""
ep_password = ""
viewclient = Viewpoint::EWSClient.new ep_user, ep_password
view_client.send_message (:subject => message.subject, :body => message.body, :body_type => "HTML")
-Raj
Solution for my problem updated on 04/27/2016
I tweaked my code in such a way to make it workable
mail(:from=>"", :to =>"", :subject => "", :doc_path => 'public/images/1.doc')
endpoint = "http:///.asmx"
ep_user = ""
ep_password = ""
viewclient = Viewpoint::EWSClient.new ep_user, ep_password
data_file = message[:doc_path].value
data = [File.open(data_file), "r"]
view_client.send_message (:subject => message.subject, :body => message.body, :body_type => "HTML", :file_attachments => data)
The send_message options hash accepts a file_attachments option as explained in the gem's code. This option should be of type Array<File>. So I guess your code would look like:
...
array_of_files = [File.join(Rails.root, 'whatever_directory', 'whatever_file.ext')]
view_client.send_message (:subject => message.subject, :body => message.body, :body_type => "HTML", :file_attachments => array_of_files)
Update:
Seems gem is broken for the case when you try to send a message with files (I think messages are just kept as drafts and not sent, only files are). So I've updated the gem to fix this case, let me know if it works correctly. Import gem from my repo like this on your Gemfile:
gem 'viewpoint', :git => 'https://github.com/durnin/Viewpoint.git'
And try the above code again. (remember to do bundle install after updating Gemfile)
For the past couple of days i've been working to improve the logstash google_bigquery connector.
Currently i was able to add features such as error handling (bad lines), better connection management and couple of other stuff.
the last but most important feature that i'm been working on is uploading compressed data to BigQuery and well the documentation of the API is horrible.
for now i'm able to uploading CSV files directly to BQ using the Jobs.insert method
and i've noted that its clearly written that data can be uploaded compressed.
the only question left is there a way i can do so without using Google Cloud Storage, as the compressed option is there to reduce the network bandwidth and its cost, and adding another route (that cost money) such as GCS is pointless
the error code i'm getting is:
BQ: job failed, please enable debug and check full response (probably
the issue is an incompatible schema). NOT deleting local file.
{:job_id=>"job_OvWTWOXGv9yGnLKfrTfGfukLytM",
:filename=>"/Users/dave.e/Logstash/tmp/bq-logstash_daves-mpb.local_2014-08-26.part000.log.gz",
:job_status=>{"state"=>"DONE",
"errorResult"=>{"reason"=>"internalError", "location"=>"File: 0",
"message"=>"Unexpected. Please try again."},
"errors"=>[{"reason"=>"internalError", "location"=>"File: 0",
"message"=>"Unexpected. Please try again."}]}, :level=>:error}
I'll cut to the main case with the code and be grateful for your help
# Uploads a local file to the configured bucket.
def upload_object(filename)
#logger.debug("entering upload_object")
begin
#logger.debug("1")
require 'json'
#logger.debug("2")
table_id = #table_prefix + "_" + get_date_pattern(filename)
#logger.debug("3")
# BQ does not accept anything other than alphanumeric and _
# Ref: https://developers.google.com/bigquery/browser-tool-quickstart?hl=en
table_id = table_id.gsub(':','_').gsub('-', '_')
#logger.debug("table bane has been modified")
#logger.debug("BQ: upload object.",
:filename => filename,
:table_id => table_id)
media = Google::APIClient::UploadIO.new(filename, "application/octet-stream")
body = {
"configuration" => {
"load" => {
"sourceFormat" => "NEWLINE_DELIMITED_JSON",
"schema" => #json_schema,
"destinationTable" => {
"projectId" => #project_id,
"datasetId" => #dataset,
"tableId" => table_id
},
'createDisposition' => 'CREATE_IF_NEEDED',
'writeDisposition' => 'WRITE_APPEND',
'maxBadRecords' => 99
}
}
}
#logger.debug("Execution details: ",
:body_object => body,
:parameters => {
'uploadType' => 'multipart',
'projectId' => #project_id
},
:media => media)
datasetId = #project_id+":"+#dataset
verify_dataset = #client.execute(:api_method => #bq.datasets.get,
:parameters => {
'projectId' => #project_id,
'datasetId' => datasetId })
status = JSON.parse(verify_dataset.response.body)["id"]
if status != dataset
#logger.info("BQ: dataset doesnt exist, creating it instead")
create_dataset = #client.execute(:api_method => #bq.datasets.insert,
:parameters => { 'projectId' => #project_id },
:body_object => { 'id' => datasetId })
sleep 10
end
insert_result = #client.execute(:api_method => #bq.jobs.insert,
:body_object => body,
:parameters => {
'uploadType' => 'multipart',
'projectId' => #project_id
},
:media => media)
job_id = JSON.parse(insert_result.response.body)["jobReference"]["jobId"]
#logger.debug("BQ: multipart insert",
:job_id => job_id)
return job_id
rescue => e
#logger.error("BQ: failed to upload file", :exception => e)
# TODO(rdc): limit retries?
sleep 1
if File.exist?(filename)
retry
end
end
end
The error on our side was that the file did not appear to be a valid gzip file, and the gzip library was unable to open it.
This could be a problem with how the file was generated or with how it was uploaded. If you still have access to the file, can you verify that you're able to unzip it?
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.
I'm trying to get Paypal SetExpressCheckout operation to add first and last name for billing. I'm using ActiveMerchant. I'm seeing the address field pre-populated (street, state, city,zip-code) but nothing else.
#### gateway ######
gateway = ActiveMerchant::Billing::PaypalExpressGateway.new(:login => 'login',:password => 'pass',:signature => 'sig')
### options ######
#options = Hash.new
#options.merge!(:ip => '127.0.0.1')
#options.merge!(:return_url => '127.0.0.1')
#options.merge!(:return_url => 'http://www.google.com')
#options.merge!(:cancel_return_url => 'http://www.google.com')
#options.merge!(:name => 'name')
#options.merge!(:description => 'description')
#options.merge!(:max_amount => 5000)
#options.merge!(:solution_type => 'Sole')
#options.merge!(:no_shipping => 1)
#options.merge!(:address_override => 1)
### build address
#address = Hash.new
#address.merge!(:name => "Joe User")
#address.merge!(:address1 => "111 ABCD EFG")
#address.merge!(:address2 => nil)
#address.merge!(:city => "Fremont")
#address.merge!(:state => "CA")
#address.merge!(:country => "US")
#address.merge!(:phone => "408-111-2222")
#options.merge!(:address => #address)
setup_response = gateway.setup_purchase(5000, #options)
redirect_to gateway.redirect_url_for(setup_response.token)
On the resultant page, I'm not seeing the name pre-filled for billing.
What am I doing wrong?
Thanks
I had the same issue as you did. After some research I came to the conclusion that this is a bug in ActiveMerchant. Please see the issue that I filed. It includes an explanation of how I patched my code to make phone number and names work:
https://github.com/Shopify/active_merchant/issues/161