Search code examples
pythonpostcurlpython-requestsasana

How to translate this curl post of an actual file to python request?


I have searched stackoverflow thoroughly, but nowhere could I find an answer to this problem.

I'm trying to contribute to asana API python wrapper. The idea is to post a file as an attachment to a task.

In the asana API docs, it is specified that the uploaded file "needs to be an actual file, not a stream of bytes."

I have a working curl request like so:

curl -u <api_key>: --form "file=@file.txt" https://app.asana.com/api/1.0/tasks/1337/attachments

Its working just fine.

I now intend to do the whole thing with request. In the request docs, all they talk about is "upload Multipart-encoded files".

So here's my actual question(s):

  1. Does "upload Multipart-encoded files" conflict with file "needs to be an actual file, not a stream of bytes"?

  2. How do I properly translate the working curl to a request post?

My go is

request.post('https://app.asana.com/api/1.0/tasks/task_id/attachments', auth=(<api_key>, ""), data={'file': open('valid_path_to_file.ext', 'rb')})

When running it, I get

{"errors":[{"message":"file: File is not an object"}]}

from asana.


Solution

  • You can pass a files parameter to requests.post for form encoded file upload. See example below:

    import requests
    
    KEY = ''
    TASK_ID = ''
    url = 'https://app.asana.com/api/1.0/tasks/{0}/attachments'.format(TASK_ID)
    
    with open('file.txt') as f:
        files = {'file': f.read()}
        r = requests.post(url, auth=(KEY, ''), files=files)
    
    print(r.status_code)
    print(r.json())