Nucklear
Nucklear

Reputation: 478

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 = 'https://api.twitter.com/oauth2/token'
    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)
    try:
        response = urllib2.urlopen(req)
        response.read()
    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
Host: api.twitter.com
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

grant_type=client_credentials

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
Host: api.twitter.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Authorization: Basic NnB1[...]YTNFOA==

grant_type=client_credentials

Any idea with what could be wrong with this?

Regards.

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

Upvotes: 3

Views: 1222

Answers (1)

Nucklear
Nucklear

Reputation: 478

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

Using base64.b64encode() instead worked fine.

Regards

Upvotes: 2

Related Questions