简体   繁体   中英

How do I write a script to call a REST API?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM