title: CURL / Ruby Alternative in Python to fetch data from API
body: <p>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.</p>
  
  <p>To get authentication token:</p>
  
  <p>Curl example:</p>
  
  <pre><code>curl -X POST -d "{\"username\" : \"user@sample.com\", \"password\":\"sample\"}" http://api.sample.com/authenticate
  </code></pre>
  
  <p>Ruby example:</p>
  
  <pre><code>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' =&gt; username, 'password' =&gt; password}.to_json
      begin
        JSON.parse(RestClient.post "#{@base_url}/authenticate", login_data, :content_type =&gt; :json, :accept =&gt; :json)['output']
      rescue Exception =&gt; 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')
  </code></pre>
  
  <p>After authentication, to get data:</p>
  
  <p>CURL example:</p>
  
  <pre><code>curl http://api.sample.com/data/day/2011-02-10/authToken/80afa08-1254-46ee-9545-afasfa4565
  </code></pre>
  
  <p>And Ruby code:</p>
  
  <pre><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' =&gt; username, 'password' =&gt; password}.to_json
  
      response = RestClient.post "#{@base_url}/authenticate", login_data, :content_type =&gt; :json, :accept =&gt; :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)
  </code></pre>
  
  <p>Thank you..</p>
  
  <p>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.</p>
  
  <p>I am new to Python and I couldn't find the right solution after reading 'urllib2' documentation and trying examples.</p>