Problems with Twitter REST API 1.1 - App Auth only response 403 Error with Python


I’m trying to connect to the twiiter API through a POST request as the docs say but I always get a 403 forbidden error.

This is my code. I’m using urlib2 in python 2.7:

def auth_API():
    url = ''
    header = {}
    values = {}
    header['User-Agent'] = 'Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'
    header['Authorization'] = 'Basic ' + B64BEARERTOKENCREDS
    header['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    header['Accept-Encoding'] = 'gzip'
    values['grant_type'] = 'client_credentials'

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, header)
        response = urllib2.urlopen(req)
    except urllib2.HTTPError as e:
        print e

Checking the docs I found an example request wich is the same as mine:

Twitter example:

POST /oauth2/token HTTP/1.1
User-Agent: My Twitter App v1.0.23
Authorization: Basic NnB1[...]9JM29jYTNFOA==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip


My request:

POST /oauth2/token HTTP/1.1
Content-Length: 29
Accept-Encoding: gzip
Connection: close
User-Agent: Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Authorization: Basic NnB1[...]YTNFOA==


Any idea with what could be wrong with this?


PS: I know that there are some third party libs for this but I want to make it by myself.


I worked with this code and with auth credentials I already knew to be functional. The code worked fine for me actually. I would make sure that the credentials are encoded correctly or aren’t in some other way incorrect.


Hi @episod this is how I’m generating the credentials:

CONSUMERKEY = "6p[...]69A" CONSUMERSECRET = "yohrE1E[...]I3oca3E8"

Derivated Constants


Could base64.encodestring() function be creating a wrong credentials string?



Did you hardcoded your credentials in my code and worked? Below you can find how I generate my B64BEARERTOKENCREDS


I solved my problem, the error was with base64.encodestring() which adds an \n at the end of the string.

Using base64.b64encode() instead worked fine.



Glad you figured out what was happening there!


Just one question, this request should return json data right?

Because when I try to read the response this is the output:

:heart:½VJLNN-.Ä/╔¤N═S▓Rr─:spades:╝|Ê:slight_smile:í╠³─♀_7cU#7▼O╦,úÓTºt╦(#▼▼¾¬░(á`╣¬▒KUÿkàSfbzEahYJZVeR║╗╣OF^HHHiPRvYZêùIÉüiüw¿ÆÄ:arrow_up_down:ÏÍ°Æ╩éTáıI®ëE®EJÁ ┬:diamonds:☼\ö


That’s likely due to your HTTP header “Accept: gzip” indicating that you’d be able to take a gzip-based response. I’m not too familiar with Python, but it might just be that you need to explicitly decompress using gzip before parsing the response.


That was my problem, thank you so much for your attention.