Search code examples
python-requestsstrava

Strava GPX upload with python module requests is giving a ValueError - why?


I don't understand why this ValueError occurs?

  • Post request
import requests

headers = {'authorization': 'Bearer XXXXXXXXXXXXXXXX'}
files = [{'file': open('../poc_data/Sport-sessions/GPS-data/2012-08-09_05-32-43-UTC_55d566fa93bc7d9d1757b8e0.gpx', 'rb')}, {'data_type': 'gpx'}, {'Content-Type': 'multipart/form-data'}]

r = requests.post('https://www.strava.com/api/v3/uploads', headers=headers, files=files)
  • Error traceback

    *Traceback (most recent call last):
    File "D:/projekte/11_github/poc_runtastic/poc_code/strava_upload_activities.py", line 19, in <module>
    r = requests.post('https://www.strava.com/api/v3/uploads', headers=headers, files=files)
    File "E:\Python\Python38\lib\site-packages\requests\api.py", line 117, in post
    return request('post', url, data=data, json=json, **kwargs)
    File "E:\Python\Python38\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, *kwargs)
    File "E:\Python\Python38\lib\site-packages\requests\sessions.py", line 528, in request
    prep = self.prepare_request(req)
    File "E:\Python\Python38\lib\site-packages\requests\sessions.py", line 456, in prepare_request
    p.prepare(
    File "E:\Python\Python38\lib\site-packages\requests\models.py", line 319, in prepare
    self.prepare_body(data, files, json)
    File "E:\Python\Python38\lib\site-packages\requests\models.py", line 512, in prepare_body
    (body, content_type) = self._encode_files(files, data)
    File "E:\Python\Python38\lib\site-packages\requests\models.py", line 141, in
    _encode_files
    for (k, v) in files:

    ValueError: not enough values to unpack (expected 2, got 1)


Solution

  • The reason for that effect regards to the API-design: it is expecting one explicit dictionary named headers and one named params.
    In my given example above I sent only one (headers) and that explains the ValueError.

    This code works:

    import requests
    
    
    files = {
        'file': open('../poc_data/Sport-sessions/GPS-data/2012-08-09_05-32-43-UTC_55d566fa93bc7d9d1757b8e0.gpx', 'rb')
    }
    headers = {
        'authorization': 'Bearer XXXXXXXXXXXXXXXX'
    }
    params = {
        'data_type': 'gpx'
    }
    url = 'https://www.strava.com/api/v3/uploads'
    
    
    r = requests.post(files=files, headers=headers, params=params, url=url)