I'm trying to do a curl post request to a REST API in rails. The cURL request I'm trying to do is:
$ curl https://api.intercom.io/events \
-X POST \
-u pi3243fa:da39a3ee5e6b4b0d3255bfef95601890afd80709 \
-H "Content-Type: application/json"
-d' { "event_name" : "invited-friend",
"created_at": 1391691571, "user_id" : "314159" }'
I've seen the many examples of using net/http for API POST requests in rails, but I never found an example that adds -u to the request. How do I do this?
We can perform a Basic Authentication by using the method basic_auth
uri = URI('http://example.com/index.html?key=value')
req = Net::HTTP::Get.new(uri)
req.basic_auth 'user', 'pass'
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
puts res.body
Figured it out. For people with a similar issue:
data = {"event_name" => "invited-friend",
"created_at" => 1391691571, "user_id" => "314159" }
uri = URI("https://api.intercom.io/events")
header = {"Content-Type" => "application/json"}
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, header)
req.basic_auth 'pi3243fa:da39a3ee5e6b4b0d3255bfef95601890afd80709', ''
req.body = data.to_json
res = https.request(req)
Related
I would like to run a curl command to request data from an API, but I'm not sure of how to do it. To transform curl request into ruby code, I'm using curl to ruby, which is great by the way.
Following the doc API, I have this :
Step 1 (Get your token) :
curl -X POST https://api.monkey-locky.com/login_check -d _username={usr}
-d _password={pwd}
I have translated this by :
require 'net/http'
require 'uri'
uri = URI.parse("https://api.monkey-locky.com/login_check")
request = Net::HTTP::Post.new(uri)
request.set_form_data(
"_password" => "my_secret_pass",
"_username" => "my#mail.co",
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
print response.body
This request give me an Token to use the API.
Step 2 (Verify if the token is working) :
curl -H "Authorization: Bearer [TOKEN]" https://api.monkeylocky.com/bookings
I have translated this by :
require 'net/http'
require 'uri'
uri = URI.parse("https://api.monkeylocky.com/bookings")
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer [TOKEN]"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
But this script is rendering an error like this :
`rescue in block in connect': Failed to open TCP connection to
api.monkeylocky.com:443 (getaddrinfo: nodename nor servname provided,
or not known) (SocketError)
I'm not very comfortable with CURL, I'm just starting to use these request. So I'm not sure of what I'm doing right now. Any suggestion about that ?
You're sending the first request to https://api.monkey-locky.com but the URL in the second request is https://api.monkeylocky.com (no dash)
I need to make HTTP get and post requests with SendGrid to add contacts to our account, however there doesn't seem to be a gem for their email marketing functionality.
It boils down to making a few requests however I can't get past their authentication step.
They say to do this
curl -X "GET" "https://api.sendgrid.com/v3/templates" -H "Authorization: Bearer Your.API.Key-HERE" -H "Content-Type: application/json"
And using the Rest-Client gem I'm trying to make the authentication request like so...
username = 'username'
api_key = 'SG.MY_API_KEY'
key = Base64.encode64(username + ":" + api_key)
headers = {"Authorization" => "Bearer #{key}", "Content-Type" => "application/json"}
response = RestClient.get 'https://api.sendgrid.com/v3/templates', headers
which returns...
RestClient::Unauthorized: 401 Unauthorized: {"errors":[{"field":null,"message":"authorization required"}]}
The ultimate objective of using their API is to add contacts.
How am I incorrectly making this get request?
I ended up figuring it out. For future reference, here's the code that worked...
require 'rest_client'
api_key = 'YOUR_API_KEY'
headers = {'Authorization' => "Bearer #{api_key}"}
data = {:email => 'email#website.com'}
response = RestClient.post 'https://api.sendgrid.com/v3/contactdb/recipients', [data].to_json, headers
To add marketing contacts to your SendGrid account via the API,
see the documentation at https://sendgrid.api-docs.io/v3.0/contacts-api-recipients/add-recipients
You can see sample code in the "code generation" section of the page.
require 'uri'
require 'net/http'
url = URI("https://api.sendgrid.com/v3/contactdb/recipients")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)
request["authorization"] = 'Bearer <<YOUR_API_KEY>>'
request["content-type"] = 'application/json'
request.body = "[{\"email\":\"example#example.com\",\"first_name\":\"\",\"last_name\":\"User\",\"age\":25},{\"email\":\"example2#example.com\",\"first_name\":\"Example\",\"last_name\":\"User\",\"age\":25}]"
response = http.request(request)
puts response.read_body
Its a RESTAPI and I need to send get request to onesignal.
url = https://onesignal.com/api/v1/apps
All they have mentioned is this:
curl --include \
--header "Authorization: Basic your_key_here" \
https://onesignal.com/api/v1/apps
I have tried something like this:
def index
url = URI.parse('https://onesignal.com/api/v1/apps?apikey=mykey')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
end
but this doesn't work.
The result should be in json.
I get this error:
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>
Based on code from OneSignal webpage your request should be:
uri = URI.parse("https://onesignal.com/api/v1/apps")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(
uri.path,
"Content-Type" => "application/json",
"Authorization" => "Basic NGXXX...XXXBlNjJj"
)
response = http.request(request)
puts response.body
In your case error was associated with not using http.use_ssl = true, but you have several other things to add, like authorization header for example.
I'm trying to replicate this GET curl request:
curl -D- -X GET -H "Authorization: Basic dGVzdEB0YXByZXNlYXJjaC5jb206NGMzMTg2Mjg4YWUyM2ZkOTY2MWNiNWRmY2NlMTkzMGU="
-H "Content-Type: application/json" http://staging.example.com/api/v1/campaigns
The auth is generated with an email + an api key this way in Ruby:
auth = "Basic" + Base64::encode64("test#example.com:4c3186288ae23fd9661cb5dfcce1930e")
What's the best way to replicate this in Ruby/Rails?
Here's what I've been trying:
auth = "Basic" + Base64::encode64("example#example.com#:4c3186288ae23fd9661cb5dfcce1930e")
uri = URI.parse("https://www.staging.example.com/api/v1/campaigns")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
request.env['HTTP_AUTHORIZATION'] = auth
response = http.request(request)
puts response.body
Based off of a few other SO's and blogs I've found, but then I get undefined method 'env' for #<Net::HTTP::Get GET> back.
Any ideas how I can set that so the message comes out like this?
Authorization: Basic dGVzdEB0YXByZXNlYXJjaC5jb206NGMzMTg2Mjg4YWUyM2ZkOTY2MWNiNWRmY2NlMTkzMGU=
request['Authorization'] = "Basic " + Base64::encode64("example#example.com#:4c3186288ae23fd9661cb5dfcce1930e")
Here's a more straightforward way, using request.basic_auth to handle all the messy details:
request = Net::HTTP::Post.new(uri)
request.basic_auth(username, password)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)
I need help in creating a post request in ruby. but i don't want to use Net::Http library. i just want to use curl commands to make post requests.
here is my existing code.
`
uri = URI.parse("http://example.com")
header = {'Content-Type' => 'application/json','Accept' => "application/json"}
req_data = {"name" => params[:user][:login], "pass" =>params[:user][:password]}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = req_data.to_json
response = http.request(request)
`
You have a chance to execute command from user's input. With Shellwords.escape should be ok.
cmd_tpl = %{curl -H "Content-Type: application/json" -H "Accept: application/json" -d "name=%s&pass=%s" %s}
cmd = cmd % [
Shellwords.escape(URI.encode(params[:user][:login])),
Shellwords.escape(URI.encode(params[:user][:password])),
Shellwords.escape("http://example.com")
]
content = `#{cmd}`