I want to get data from an API using Python. The API documentation give examples in CURL and Ruby. I would be very happy if you can post code snippets on how to do the following things with Python.
To get authentication token:
Curl example:
curl -X POST -d "{\"username\" : \"user@sample.com\", \"password\":\"sample\"}" http://api.sample.com/authenticate
Ruby example:
require 'rubygems'
require 'rest_client'
require 'json'
class AuthorizationClient
attr_accessor :base_url
def initialize(base_url)
@base_url = base_url
end
def authenticate(username,password)
login_data = { 'username' => username, 'password' => password}.to_json
begin
JSON.parse(RestClient.post "#{@base_url}/authenticate", login_data, :content_type => :json, :accept => :json)['output']
rescue Exception => e
JSON.pretty_generate JSON.parse e.http_body
end
end
end
client = AuthorizationClient.new('http://api.sample.com/authenticate')
puts client.authenticate('user@sample.com','sample')
After authentication, to get data:
CURL example:
curl http://api.sample.com/data/day/2011-02-10/authToken/80afa08-1254-46ee-9545-afasfa4565
And Ruby code:
require 'rubygems'
require 'rest_client'
require 'json'
class ReportingClient
attr_accessor :auth_token, :base_url
def initialize(base_url)
@base_url = base_url
end
def authenticate(username,password)
login_data = { 'username' => username, 'password' => password}.to_json
response = RestClient.post "#{@base_url}/authenticate", login_data, :content_type => :json, :accept => :json
@auth_token = JSON.parse(response)['output']
end
def get_report(start_date, end_date)
response = RestClient.get "#{@base_url}/data/day/#{day}/authToken/#{auth_token}"
JSON.parse(response)
end
end
client = ReportingClient.new('http://api.sample.com:20960')
client.authenticate('user@sample.com','sample')
results = client.get_report('2011-02-10')
puts JSON.pretty_generate(results)
Thank you..
PS: I am aware of pycurl. But I am not sure if I really need it. I am happy with using Python native libraries. Pycurl might be over-kill for my needs.
I am new to Python and I couldn’t find the right solution after reading ‘urllib2’ documentation and trying examples.
This is not a port but it looks like you are sending a POST and then obtaining the authorization token and then sending a GET request using this.
This is based on what I understood.