Using Rest Client to post a curl in rails - ruby-on-rails

I want to traduce this curl into rest client sintax:
curl https://sandbox-api.openpay.mx/v1/mzdtln0bmtms6o3kck8f/customers/ag4nktpdzebjiye1tlze/cards \
-u sk_e568c42a6c384b7ab02cd47d2e407cab: \
-H "Content-type: application/json" \
-X POST -d '{
"token_id":"tokgslwpdcrkhlgxqi9a",
"device_session_id":"8VIoXj0hN5dswYHQ9X1mVCiB72M7FY9o"
}'
The hash I already have it in a variable and the keys or id´s are static so I paste them wherever I need to. This is what I´ve done so far but it doesn't work:
response_hash=RestClient.post "https://sandbox-api.openpay.mx/v1/mdxnu1gfjwib8cmw1c7d/customers/#{current_user.customer_id}/cards \
-u sk_083fee2c29d94fad85d92c46cec26b5a:",
{params: request_hash},
content_type: :json, accept: :json
Can someone help me traduce it?

Try this:
begin
RestClient.post(
"https://sk_e568c42a6c384b7ab02cd47d2e407cab:#sandbox-api.openpay.mx/v1/mzdtln0bmtms6o3kck8f/customers/ag4nktpdzebjiye1tlze/cards",
{ token_id: 'tokgslwpdcrkhlgxqi9a', device_session_id: '8VIoXj0hN5dswYHQ9X1mVCiB72M7FY9o' }.to_json,
{ content_type: :json, accept: :json }
)
rescue RestClient::ExceptionWithResponse => e
# do something with e.response.body
end

Related

How do I convert this curl command to Ruby rest-client put request?

I have this curl command which I need to covert to PUT request
curl https://example.com/api/v2/students/id.json \
-d '{"student":{"description":{"body":"Adding a new test description"}}}' \
-H "Content-Type: application/json" \
-v -u test#gmail.com:Abcd1234 \
-X PUT
Trial
I tried this PUT, but it doesn't work. It doesn't throw any error, but it does not add the description.
put(
"https://example.com/api/v2/students/id.json",
{:student => {:description => {:body => 'Adding a new test description.'}}},
{ 'Authorization' => "Basic #{authorization_token}" }
)
In your curl example, you provided the body as a (JSON-formatted) string:
curl ... \
-d '{"student":{"description":{"body":"Adding a new test description"}}}' \
...
The direct equivalent in rest-client would also use a (JSON-formatted) string:
put( ...,
'{"student":{"description":{"body":"Adding a new test description"}}}',
...
)
According to the README:
rest-client does not speak JSON natively, so serialize your payload to a string before passing it to rest-client.
You can use the rest-client log to show the actual HTTP request sent, and compare it with what curl sends.
How to debug/display request sent using RestClient
How to display request headers with command line curl
curl https://example.com/api/v2/students/id.json \
-d '{"student":{"description":{"body":"Adding a new test description"}}}' \
-H "Content-Type: application/json" \
-v -u test#gmail.com:Abcd1234 \
-X PUT
use
put(
"https://test%40gmail.com:Abcd1234#example.com/api/v2/students/id.json",
{student: {description: {body: 'Adding a new test description.'}}},
#{'student': {'description': {'body': 'Adding a new test description.'}}},
#{:student => {:description => {:body => 'Adding a new test description.'}}}.to_json,
{content_type: :json, accept: :json}
)

Ruby Gem Rest-Client vs cURL, HTTP 415

I have a cURL call that works but when I translate it using the Ruby Gem rest-client I get:
RestClient::UnsupportedMediaType: 415 Unsupported Media Type
Here is the cURL I used that worked:
curl \
-X POST \
-H "Content-Type:application/json" \
-H "Authorization: Bearer MY_TOKEN" \
-H "Amazon-Advertising-API-Scope: MY_SCOPE" \
-d '{"campaignType":"sponsoredProducts","reportDate":"20161013","metrics":"impressions,clicks,cost"}' \
https://advertising-api.amazon.com/v1/productAds/report
Here is the Ruby that returns the HTTP 415 status:
yesterday = Date.today - 1
RestClient::Request.execute(
method: :post,
url: 'https://advertising-api.amazon.com/v1/productAds/report',
headers:
{
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{ENV['AD_ACCESS_TOKEN']}",
'Amazon-Advertising-API-Scope' => ENV['AD_PROFILE_ID']
},
payload:
{
'campaignType' => 'sponsoredProducts',
'reportDate' => "#{yesterday.year}#{yesterday.month}#{yesterday.day}",
'metrics' => 'impressions,clicks,cost'
}
)
The payload hash needed to be converted to JSON.
...
payload:
{
...
}.to_json
...

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" }
)

How to reading and Output [FILTERED] value from parameters in Ruby

I am using curl to post json to my example service. I am posting json to the service as shown below
curl \
> -i \
> -H "Accept: application/json" \
> -H "Content-type: application/json" \
> -X POST \
> -d '{"email":"micky#minn.com","full_names":"Inisne Dats", "password": "oasswn"}' http://localhost:3000/api/admin_users
Below is my method thats responsible for creating and saving the new Active record Object
def create
user = AdminUser.new(white_list)
if user.save
head 200
else
puts user.errors.full_messages
head 500
end
end
My Whitelist method below
private
def white_list
params.require(:admin_user).permit(:email,:full_names,:password)
end
The problem is that this code never saves because the password is FILTERED, I have inspected the parameters and this is the output;
{"email"=>"micky#minn.com", "full_names"=>"Inisne Dats", "password"=>"[FILTERED]", "admin_user"=>{"email"=>"micky#minn.com", "full_names"=>"Inisne Dats"}}
Can anyone help show me how to retrieve the filtered password and use it once the parameters reach the controller method create. Or I'm I using whitelisting feature wrong?
#j-dexx gave me this answer. I had to wrap the parameters with a root "admin_user" key like so:
{ "admin_user":
{ "email": "micky#minn.com",
"full_names": "Inisne Dats",
"password": "oasswn",
"password_confirmation": "oasswn"
}
}
...so I changed my post request to:
curl \
> -i \
> -H "Accept: application/json" \
> -H "Content-type: application/json" \
> -X POST \
> -d '{"admin_user":{"email":"micky#minn.com","full_names":"Inisne Dats","password":"oasswn","password_confirmation":"oasswn"}}' http://localhost:3000/api/admin_users
That did the trick!

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
)

Resources