Issuing application-only requests in Twitter 1.1 using Python
Question: I want to access Twitter 1.1 search endpoint using application-only
authentication. To do the same, I'm trying to implement the steps given on
Twitter API's documentation here -
<https://dev.twitter.com/docs/auth/application-only-auth> (scroll to "Issuing
application-only requests")

I am not able to obtain the "bearer token" in Step 2. When I run the following
code, I receive "Response: 302 Found" which is a redirection to Location:
<https://api.twitter.com/oauth2/token> Ideally it should be "200 OK"

    
    
    import urllib
    import base64
    import httplib
    
    CONSUMER_KEY = 'my_key'
    CONSUMER_SECRET = 'my_secret'
    
    encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
    encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)
    
    concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET
    
    host = 'api.twitter.com'
    url = '/oauth2/token'
    params = urllib.urlencode({'grant_type' : 'client_credentials'})
    req = httplib.HTTP(host)
    req.putrequest("POST", url)
    req.putheader("Host", host)
    req.putheader("User-Agent", "My Twitter 1.1")
    req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
    req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
    req.putheader("Content-Length", "29")
    req.putheader("Accept-Encoding", "gzip")
    
    req.endheaders()
    req.send(params)
    
    # get the response
    statuscode, statusmessage, header = req.getreply()
    print "Response: ", statuscode, statusmessage
    print "Headers: ", header
    

I do not want to use any Twitter API wrappers to access this.


Answer: The problem was that the URL had to be called with an HTTPS connection. Please
check the modified code which works.

    
    
    import urllib
    import base64
    import httplib
    
    CONSUMER_KEY = 'my_key'
    CONSUMER_SECRET = 'my_secret'
    
    encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
    encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)
    
    concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET
    
    host = 'api.twitter.com'
    url = '/oauth2/token/'
    params = urllib.urlencode({'grant_type' : 'client_credentials'})
    req = httplib.HTTPSConnection(host)
    req.putrequest("POST", url)
    req.putheader("Host", host)
    req.putheader("User-Agent", "My Twitter 1.1")
    req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
    req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
    req.putheader("Content-Length", "29")
    req.putheader("Accept-Encoding", "gzip")
    
    req.endheaders()
    req.send(params)
    
    resp = req.getresponse()
    print resp.status, resp.reason
    

