I am trying to perform a simple PUT with JSON data in the tastypie-Django Python application. But I'm seeing a 401 response error when I call it through code, but no error when I execute a cURL command from the terminal. I have the code:
data_to_update = json.dumps({ "NAME" : username,
"type": mytype
})
headers = { "Content-type": "application/json",
"Authorization: ApiKey": '{0}:{1}'.format(username, key)
}
conn = httplib.HTTPConnection('localhost:8000')
conn.set_debuglevel(1)
conn.request('PUT', '/api/v1/table/1/', data_to_update, headers=headers)
response = conn.getresponse()
print response.status, response.reason
conn.close()
and I see the output:
send: u'PUT /api/v1/table/10/ HTTP/1.1\r\nHost: localhost:8000\r\nAccept-Encoding: identity\r\nContent-Length: 148\r\nContent-type: application/json\r\nAuthorization: ApiKey: api:79910a14-a82c-41f9-bb79-458247e6b31a\r\n\r\n{"username": "johnny", "type": "admin_user", "resource_uri": "/api/v1/table/10/"}'
reply: 'HTTP/1.0 401 UNAUTHORIZED\r\n'
header: Date: Fri, 15 Aug 2014 20:07:36 GMT
header: Server: WSGIServer/0.1 Python/2.7.5
header: X-Frame-Options: SAMEORIGIN
header: Content-Type: text/html; charset=utf-8
401 UNAUTHORIZED
But when I run the cURL
command via terminal:
curl -X PUT -v -H "Content-Type: application/json" -H "Authorization: ApiKey api:79910a14-a82c-41f9-bb79-458247e6b31a" --data '{"username": "johnny", "type": admin_user, "resource_uri": "/api/v1/table/1/"}' http://localhost:8000/api/v1/table/10/
And it works. (It results in 204 NO CONTENT
, which is expected). However, I can't find any differences between these two calls and their data. Does anyone have any ideas or pointers where I'm going wrong here?
"Authorization: ApiKey": '{0}:{1}'.format(username, key)
That's not a valid header. It should look like this:
"Authorization": 'ApiKey {0}:{1}'.format(username, key)
With your code you were sending this (in my opinion a decent library should raise an exception since a header name cannot contain a colon):
Authorization: ApiKey: username:key
instead of this:
Authorization: ApiKey username:key