Reputation: 32244
When using the following code to connect to the toggl api I connect and am authorised just fine.
username = token
password = 'api_token'
url = 'http://www.toggl.com/api/v3/tasks.json'
req = urllib2.Request(url)
auth_string = base64.encodestring('%s:%s' % (username, password))
req.add_header("Authorization", "Basic %s" % auth_string)
f = urllib2.urlopen(req)
response = f.read()
When I try to start a new task I have to send data in json format. To test, I created my json object and added the data to my Request object
data = simplejson.dumps({
'task':{
'duration': 1,
'billable': True,
'start': '2010-02-12T16:19:45+02:00',
'description': 'This is a test task',
}
})
req = urllib2.Request(url, data)
But now the only response I recieve is "urllib2.HTTPError: HTTP Error 400: Bad Request". Can someone please point me to where I am going wrong?
Upvotes: 2
Views: 3899
Reputation: 32244
I have figured it out. Thanks to TryPyPy, I needed to add a 'Content-type' header to my request.
I had to strip any newline and linefeed characters from my authentication string.
auth_string = base64.encodestring('%s:%s' % (username, password)).strip()
Upvotes: 2
Reputation: 6434
According to the API documentation, you're missing at least a header. Try:
req = urllib2.Request(url, data, {"Content-type": "application/json"})
If that's not enough, try using urllib.urlencode on data. If that's still not enough, add a user:password to the request, like in the API example.
Upvotes: 3