Upload a single file with Python
I want to upload a single file to Workiva and associate it with an existing table using this endpoint in Python.
My code:
import requests
headers = {
'Authorization': f'Bearer {access_token}', # I've got an access_token from the Workiva authentication API
# 'Content-Type': 'multipart/form-data' # If I set this, the API will respond '{"body":"No multipart boundary parameter in Content-Type","code":400,"details":null}'
}
file_name = 'test.csv'
table_id = '643ff5b61d0742769d25fe579b53521a'
url = 'https://h.eu.wdesk.com/s/wdata/prep/api/v1/file'
params = {
'tableId': table_id
}
with open(file_name, 'rb') as file_to_upload:
# print(file_to_upload.readline()) -> this works fine
files = {
'file': (file_name, file_to_upload)
}
r = requests.post(url, params=params, headers=headers, files=files)
print(r.status_code) # -> prints 400
print(r.request.headers) # shows that the Content-Type is set correctly, including the boundary
print(r.request.body) # shows the file content I'm sending
print(r.content)
The API responds with '{"body":["contentType must not be null"],"code":400,"details":null}'. However, this is misleading, because in the header I can clearly see that the Content-Type is set correctly, including the boundary.
If I set the Content-Type manually, the API complains that no boundary is set. If I set the boundary manually, I get an EOF reached error, i.e. I can't set the boundary manually (the boundary must be calculated, not set manually).
I can successfully upload my csv-file via Postman, so the csv-file should be fine, as well as my understanding of how to use the API.
Am I doing something wrong or is this a bug in the Workiva API code?
-
The issue is easily resolved by specifying the MIME-type of the file:
files = {
'file': (file_name, file_to_upload, 'text/csv')
}1Please sign in to leave a comment.
Comments
1 comment