pythoncurlurllib2box-apibox-view-api

urllib2.urlopen error on Box API - can't convert to proper string


I am trying to send a POST to the Box API but am having trouble with sending it through Python. It works perfectly if I use curl:

curl https://view-api.box.com/1/sessions \
-H "Authorization: Token YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"document_id": "THE_DOCUMENT_ID", "duration": 60}' \
-X POST

But with my python code I get a HTTP Error 400: BAD REQUEST

headers = {'Authorization' : 'Token '+view_api_key, 'Content-Type' : 'application/json'}
session_data = {"document_id" : doc_id, "duration": 60}
session_data = urllib.urlencode(session_data)
session_request = urllib2.Request("https://view-api.box.com/1/sessions", session_data, headers)
session_response = urllib2.urlopen(session_request)

The problem lies in my session_data. It needs to be a buffer in the standard application/x-www-form-urlencoded format (http://docs.python.org/2/library/urllib2.html), so I do a urlencode, however the output is 'duration=60&document_id=MY_API_KEY', which does not preserve { } format.

Any ideas?


Solution

  • For the View API (and the Content API), the body data, session_data in your code, needs to be encoded as JSON.

    All you need to do is import the json module at the beginning of your code (i.e. import json) and then change

    session_data = urllib.urlencode(session_data)
    

    to

    session_data = json.dumps(session_data)
    

    dumps() converts the python dict into a JSON string.

    (as a sidenote, I would highly recommend not using urllib and using the Requests library instead.)