Roger C.
Roger C.

Reputation: 41

Ruby on Rails curl POST request with user authentication

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?

Upvotes: 2

Views: 1419

Answers (2)

Roger C.
Roger C.

Reputation: 41

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)

Upvotes: 2

Bruno Bispo
Bruno Bispo

Reputation: 101

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

Upvotes: 2

Related Questions