upload image with soundcloud api - ruby

I keep getting an error everytime I try to change the souncloud avatar by uploading, I'm guessing something is wrong with my api wrapper layout? I get a
"`handle_response': HTTP status: 500 Internal Server Error (SoundCloud::ResponseError)"
"HTTP status: 403 Forbidden (SoundCloud::ResponseError)
from /Users/.../.rvm/gems/ruby-2.2.0/gems/soundcloud-0.3.2/lib/soundcloud/client.rb:32:in `post'"
My code:
require 'soundcloud'
user = Soundcloud.new(:client_id => '...',
:client_secret => '...',
:username => '...',
:password => '...')
avatar_data = File.path("/path/to/file/-1.jpg")
user.post('/me').avatar_data
I also tried:
testuser.post('/me/#{avatar_data}')

Related

In ruby with sinatra, How to get I response with get method on rest client?

I use ruby with sinatra and I used rest-client on import for payment.
I got token that string typed through post method on specific url: '... /users/getToken'.
Using this token, I wanna get payments information with get method on this url:
get_url = 'https://api/iamport.kr/payments/'+imp_uid
the detail codes are below,
def get_paymentsdetails(token, imp_uid)
get_url = 'https://api.iamport.kr/payments/'+imp_uid
response = RestClient.get get_url, :data => {}.to_json, :accept => :json, :headers => {'Authorization' => token}
json = JSON.parse(response, :symbolize_names => true)
# json = JSON.parse(response.to_json, {:symbolize_names => true})
return json
end
However, I got 401 unauthorized error on this part of code.
response = RestClient.get get_url, :data => {}.to_json, :accept => :json, :headers => {'Authorization' => token}
After I access get_url with specific imp_uid, I got this page,{"code":-1,"message":"Unauthorized","response":null}
I checked parameter token and imp_uid of get_paymentsdetails function have valid string values,, so How can I access response parameter??
I think that there are some problems on response = RestClient.get get_url.... code.
Thanks.
Method 'get' from the 'RestClient' class return some object with attributes. So response have few values. Which of them do you need? Access to them you can get by their names, its described here.
In your case, after response = RestClient.get get_url... you should have variable response and ability to call response.headers, response.code or response.body.
But im afraid that you have some problems with autorization, which means that imp_uid or token is not correct. Thats why remote server sended to you responce with http-code 401 (Unauthorized). If it is so you should try to check your imp_uid and token. If everything is correct try to reach support of iamport.kr .

Can't add email to Campaign Monitor API?

I am trying to create some simple Ruby code to add emails using the Campaign Monitor API. Below is my code.
require 'httparty'
require 'json'
def request
url = 'https://api.createsend.com/api/v3.1/subscribers/MYLISTID.json'
auth = {:username => 'MYAPIKEY', :password => 'x'}
response = HTTParty.post(url,
:basic_auth => auth, :body => {
'EmailAddress' => 'mike#hotmail.com',
'Name' => 'Test',
'Resubscribe' => true,
'RestartSubscriptionBasedAutoresponders' => true
})
puts response
puts response.code
end
request
I can connect with the API. However, when I try to add the email I am getting the following response.
{"Code"=>400, "Message"=>"Failed to deserialize your request.
Please check the documentation and try again.
Fields in error: subscriber"}
400
When I change the request to get instead of put
my response is:
{"Code"=>1, "Message"=>"Invalid Email Address"}
I can't understand what I am doing wrong as I have followed the documentation on the Campaign Monitor API
It looks like you have everything setup correctly, you just need to turn the body of the post into a json string.
response = HTTParty.post(url,
:basic_auth => auth, :body => {
'EmailAddress' => 'mike#hotmail.com',
'Name' => 'Test',
'Resubscribe' => true,
'RestartSubscriptionBasedAutoresponders' => true
}.to_json)
I'd like to point out that a Campaign Monitor API gem also exists that will do all of that work for you.
Campaign Monitor API Gem

How do I use RestClient to post as URL params?

I am posting to an API which accepts CURL as follows:
curl -v -X POST "https://url.com" -d 'input=frustrated&user_key=3b9ccb48e734fce6b982a9c1c2cef301'
I have tried the following with an error:
data = {'user_key' => "#{ENV['USER_KEY']}", 'input' => "#{text}", 'client_name'=>> "#{client_name}"}
talkresponse = JSON.parse(RestClient.post url_talk_bot, {:params => data})
for some reason, the data is fine for all except for 'input' which always gets an error as an array which triggers an error since a string is expected. Note below how the input params is an array.
{"user_key"=>"3b9ccb48e734fce6b982a9c1c2cef301", "input"=>"[\"frustrated how do I post to params, worked fine before\"]", "client_name"=>"14155086888"}
/mnt/task/__gems__/gems/rest_client-1.7.3/lib/restclient/abstract_response.rb:48:in `return!': 401 Unauthorized (RestClient::Unauthorized)
I have run into similar issues when using RestClient.post.
So much so, that I stopped using .post and started using .execute
RestClient.post uri, {:params => data}
becomes
RestClient.execute({ :method => :post, :url => uri, :headers => {api_key: '123', authorization: Base64::encode("#{user}:#{password}"}, :payload: body})

Google API Ruby Client - single user with OAuth 2.0

the goal is to have one Google (YouTube) account for the web app. Users of the web app will be able to upload videos via this account to the one YouTube channel. After many hours im in the ends. I've found plenty of samples how to implement for Google user <-> web app interaction, but I don't need such comprehensive solution.
I'm trying over OAuth 2.0 (as recommended) and with Google API Ruby Client (https://github.com/google/google-api-ruby-client)
So far I have authorized the Google account (which will have that YouTube channel) with the web app, all necessary scopes included, offline access too and I have mechanism for refreshing access token. So I have access token, refresh token, client id and client secret.
But I don't know how to send a simple authorized request. The result below returns me "Daily Limit for Unauthenticated Use Exceeded." after a while so something wrong - i guess im missing part with client id and client secret.
So the question is: How to send simply authorized request via OAuth 2.0 with Google API Ruby Client, when we work with only one user and we have all necessary ids, secrets and tokens?
Thanks for any help or suggestion.
# Faraday connection
conn = Faraday.new(:url => 'https://accounts.google.com',:ssl => {:verify => false}) do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
# Refresh token
result = conn.post '/o/oauth2/token', {
'refresh_token' => "1/1lDIvifN******************dk9Akuc9ELVKM0",
'client_id' => "61********506.apps.googleusercontent.com",
'client_secret' => "********************g_dLfKmi",
'grant_type' => 'refresh_token'}
#output = ActiveSupport::JSON.decode result.body
#access_token = #output['access_token']
#token_type = #output['token_type']
# Google Client
client = Google::APIClient.new
# YouTube API v3
api = client.discovered_api('youtube', 'v3')
# Retrieve list of playlists (not working)
#result = client.execute(
:api_method => api.playlists.list,
:parameters => {'part' => 'snippet', 'mine' => 'true'},
:authorization => {'token_type' => #token_type, 'access_token' => #access_token}
)
Ok, so I though the :authorization param in the execute request will add HTTP header Authorization: token_type access_token itself, but not and it was a problem.
So this works:
#result = client.execute(
:api_method => api.playlists.list,
:parameters => {'part' => 'snippet', 'mine' => 'true'},
:authorization => {:token_type => #token_type, :access_token => #access_token},
:headers => {:authorization => #token_type + ' ' + #access_token}
)

Ruby Multi-part Form Upload with RestClient

I'm working on a ruby application, and am trying to upload a file to box.net. I have it working with the curl call
curl https://www.box.com/api/2.0/files/data -H "Authorization: BoxAuth api_key=<API_KEY>&auth_token=<AUTH_TOKEN>" -F folder_id=0 -F filename=#test.txt --trace ~/Desktop/log.txt
I've tried to translate this into ruby, and have tried the following
request = RestClient::Request.new(:method => :post,:url => "https://www.box.com/api/2.0/files/data",:authorization => "BoxAuth api_key=<API_KEY>&auth_token=<AUTH_TOKEN>",:filename => "test.txt", :payload => { :multipart => true, :file => File.new("test.txt"))
request.execute
but I keep getting back a "401: Unauthorized" response. I've also tried using the box-api gem, but that seems to only work with version 1.0 of the API, and I'm trying to interface with 2.0.
Try to use :headers => {:authorization => "BoxAuth api_key=<API_KEY>&auth_token=<AUTH_TOKEN>"} in the call. That should fix the missing authorization header.
Complete request would then be:
request = RestClient::Request.new(:method => :post,:url => "https://www.box.com/api/2.0/files/data",:headers => {:authorization => "BoxAuth api_key=<API_KEY>&auth_token=<AUTH_TOKEN>"},:filename => "test.txt", :payload => { :multipart => true, :file => File.new("test.txt")})

Resources