Reputation: 310
I want to write a script which calls a REST API using a URL like:
http://localhost:3000/api/v1/user/xyz
If I open this URL in the browser, it asks for a user email and password. Once I've authenticated, it returns a JSON response with a user id. I don't know how I should I authenticate through the script. Can someone give me a suggestion?
This is what I started with:
require 'rubygems'
require 'net/http'
require 'json'
api_url = "http://localhost:3000/api/v1//user/xyz"
response = Net::HTTP.get_response(URI.parse(api_url))
data = JSON.parse(response.body)
fields = data.keys
puts fileds
puts data.keys
This is the authentication for the API:
before_filter :authorize, :except => [:keys]
private
def authorize
authenticate_or_request_with_http_basic do |username, password|
user = User.find_by_email(username)
if user && user.valid_password?(password)
sign_in :user, user
end
end
end
How I can pass email and password to authenticate this API so I can get "id" as return?
Upvotes: 0
Views: 10340
Reputation: 186984
HTTP Basic authentication is pretty simple to add to your request, though I don't think you can use the get_response
convenience method.
See: http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Basic+Authentication
Example from the documentation:
uri = URI('http://example.com/index.html?key=value')
req = Net::HTTP::Get.new(uri)
req.basic_auth 'user', 'pass' # username, password go here.
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
puts res.body
Upvotes: 1
Reputation: 895
rest_client gem works great for me. As far as what the API returns that should be in the documentation. You can always try it in IRB and see what the response contains.
Upvotes: 1