HTTParty - how to generate authorisation id from username and password - ruby-on-rails

I use the following curl command on the command line to generate a token id which I then use in the HTTParty code.
curl -d "username=Yoshi.Nosaka#test.com&password=testpwd" http://upload.test.org:8026/api2/auth-token/
The above curl command generates the token id:
6cb2997265877d4cee5467e93577fa
I then use the token id in HTTParty commands in my rails application. Example:
HTTParty.get("http://upload.test.org:8026/api2/repos/", :headers => { "Authorization" => "Token 6cb2997265877d4cee5467e93577fa"})
I would like to know how to generate that token id using HTTParty in my rails app, rather than doing it on the command line.
Thanks a lot for all your suggestions.

cURL -d option send data on a POST.
curl -d "username=Yoshi.Nosaka#test.com&password=testpwd" http://upload.test.org:8026/api2/auth-token/
I don't know if your app handles json requests. But if so, you can use something like the above.
HTTParty.post("http://upload.test.org:8026/api2/auth-token/",
{
:body => [ { "username" => "Yoshi.Nosaka#test.com", "password" => "testpwd" } ].to_json,
:headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}
})

Related

Showing 400 bad request when try to post file via rest API with Ruby

I'm try to post a file using RestClient with Ruby on rails, I have try to conver below curl command:
curl -H 'Authorization: Bearer ACCESS_TOKEN' -F 'file=#FILE_PATH' https://api.com/api
When converting with RestClient like below:
res = RestClient::Request.new(
method: :post,
url: 'https://api.com/api',
:payload => {
:file => File.new("#{Rails.root}/public/Sample.docx" , 'rb')
},
:headers => {
:Authorization => "Bearer 155c5e5c4feea51b386fdfe204abc60b7f4025fb91988519de869525217b4702",
:content_type => "multipart/form-data"
}
)
res.execute
On this code showing 400 Bad Request
What I'm doing wrong with this code?
Thanks
Your post is a duplicate of this one Ruby - Uploading a file using RestClient post
In your case, try changing content_type to application/vnd.openxmlformats-officedocument.wordprocessingml.document
List of MIME types can be found here: What is a correct mime type for docx, pptx etc?

curl post request in rails controller

I want to convert this post request written in curl (GoPay payment gateway) to my Rails application:
curl -v https://gw.sandbox.gopay.com/api/oauth2/token \
-X "POST" \
-H "Accept: application/json" \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "<Client ID>:<Client Secret>" \
-d "grant_type=client_credentials&scope=payment-create"
I am trying to do in my rails controller by using a gem rest-client. I've done something like this and was modifiying many times but couldn't make it works:
RestClient::Request.execute( method: :post,
url: "https://gw.sandbox.gopay.com/api/oauth2/token",
"#{ENV['GOPAY_CLIENT_ID']}": "#{ENV['GOPAY_CLIENT_SECRET']}"
data: "grant_type=client_credentials&scope=payment-create"
)
How I can convert the curl post request for the rest-client (or similar)?
EDIT: It is showing a status code 409: Conflict with no further information
EDIT1 - rgo's modified code works, thank you:
RestClient.post "https://#{ENV['GOPAY_CLIENT_ID']}:#{ENV['GOPAY_CLIENT_SECRET']}#gw.sandbox.gopay.com/api/oauth2/token",
{ grant_type: 'client_credentials', scope: 'payment-create'},
content_type: :json, accept: :json
I'm not a RestClient user but after reading the documentation[1] I think I transformed your cURL request to RestClient:
RestClient.post "http://#{ENV['GOPAY_CLIENT_ID']}:#{ENV['GOPAY_CLIENT_SECRET']}#https://gw.sandbox.gopay.com/api/oauth2/token",
{ grant_type: 'client_credentials', scope: 'payment-create'},
content_type: :json,
accept: :json
As you can see I pass the credentials in the URL because is a basic authentication. Data(grant_type and scope) is passed as hash and then converted to JSON. Then we set rest client to send and receive JSON.
I hope it helps you
[1] https://github.com/rest-client/rest-client#usage-raw-url
You didn't mention exactly what doesn't work or what error you're seeing. However, the -u option for curl is used to pass the username and password for basic authentication.
The equivalent for RestClient is to use the user and password options e.g.
RestClient::Request.execute(
method: :post,
url: "https://gw.sandbox.gopay.com/api/oauth2/token",
user: "#{ENV['GOPAY_CLIENT_ID']}",
password: "#{ENV['GOPAY_CLIENT_SECRET']}"
data: "grant_type=client_credentials&scope=payment-create",
headers: { "Accept" => "application/json", "Content-Type" => "application/x-www-form-urlencode" }
)

Convert curl command to httparty

I am trying to add merge field in Mailchimp V3 list with HTTParty but not able to convert curl to HTTParty format.
Curl Request format which is working fine :
curl --request POST \
--url 'https://usxx.api.mailchimp.com/3.0/lists/17efad7sd4/merge-fields' \
--user '12:d1c1d99dr5000c63f0f73f64b88e852e-xx' \
--header 'content-type: application/json' \
--data '{"name":"FAVORITEJOKE", "type":"text"}' \
--include
Httparty format with error API key missing
response = HTTParty.post("https://us12.api.mailchimp.com/3.0/lists/17efad7sde/merge-fields",
:body => {
:user => '12:d1c1d99dr5000c63f0f73f64b88e852e-xx',
:data => '{"name":"FAVORITEJOKE", "type":"text"}',
:include => ''
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
I also try it without include option but not working
There are several errors in your code.
curl user is the basic auth user, but you are passing it in the payload of the request
data is the payload, instead you are passing it as a node in your payload and then you double serialize it
include makes no sense there, it's not a payload item
This should be the correct version. Please take a moment to read the HTTParty and curl documentation and understand the differences.
HTTParty.post(
"https://us12.api.mailchimp.com/3.0/lists/17efad7sde/merge-fields",
basic_auth: { username: "12", password: "d1c1d99dr5000c63f0f73f64b88e852e-xx" },
headers: { 'Content-Type' => 'application/json' },
body: {
name: "FAVORITEJOKE",
type: "text",
}.to_json
)

Rails RestClient pass token in header fails

I do this curl in Terminal which works excellent:
$ curl https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000 -H "Authorization: Token xxxxxxxxxxxxxxxxxxxxxx"
Output is json.
Now I want to access the json string via my rails app. I have tried RestClient to do this, but somehow I always get a 401 unauthorized error. I believe the token gets not send correctly via header. I have tried the following:
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', {token: 'xxxxxxxxxxxxxxxxxxxxxx'}
and
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', :params => {:token => 'xxxxxxxxxxxxxxxxxxxxxx'}
with no success. Maybe I use a wrong syntax for sending the token in the header?
Doku is here http://rubydoc.info/github/rest-client/rest-client - I could not find any mistakes.
# GET request with modified headers
RestClient.get 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# POST request with modified headers
RestClient.post 'http://example.com/resource', {:foo => 'bar', :baz => 'qux'}, {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# DELETE request with modified headers
RestClient.delete 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
Source: https://github.com/rest-client/rest-client#headers

Convert Curl command line in Rails

This is my curl command which works nicely in Command line :
curl --data #order_new.json \
-H "X-Augury-Token:My_token_goes_here" \
-H "Content-Type:application/json" \
http://staging.hub.spreecommerce.com/api/stores/store_id_goes_here/messages
I need to implement the same in rails using any sort of Gem, Tried with HTTParty /rest_client / spree-api-client, but something wrong here :
require 'httparty'
result = HTTParty.post(
"http://staging.hub.spreecommerce.com/api/stores/52eb347f755b1c97e900001e/messages",
:body => JSON.parse(File.read("order_new.json")),
:header => {
"X-Augury-Token" => "UjjKsdxbrwjpAPx9Hiw4",
"Content-Type" => "application/json"
}
)
But I am getting Error,
"The page you were looking for doesn't exist (404)"
I need rails equivalent of above curl command, use of spree-api-client gem will be much helpful.
If you prefer to use the Spree::API::Client, could you post the results of your findings? Could you evaluate the output of the following commands and post back:
client = Spree::API::Client.new('http://staging.hub.spreecommerce.com/api/', 'UjjKsdxbrwjpAPx9Hiw4')
client.products.inspect
require 'httparty'
result = HTTParty.post(
"http://staging.hub.spreecommerce.com/api/stores/52eb347f755b1c97e900001e/messages",
:body => #order.to_json,
:header => {
"X-Augury-Token" => "UjjKsdxbrwjpAPx9Hiw4",
"Content-Type" => "application/json"
}
)
Don't parse json while passing to HTTParty body

Resources