Search code examples
pythonrestpython-3.xmultipart

Python 3 script to upload a file to a REST URL (multipart request)


I am fairly new to Python and using Python 3.2. I am trying to write a python script that will pick a file from user machine (such as an image file) and submit it to a server using REST based invocation. The Python script should invoke a REST URL and submit the file when the script is called.

This is similar to multipart POST that is done by browser when uploading a file; but here I want to do it through Python script.

If possible do not want to add any external libraries to Python and would like to keep it fairly simple python script using the core Python install.

Can some one guide me? or share some script example that achieve what I want?


Solution

  • Requests library is what you need. You can install with pip install requests.

    http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file

    >>> url = 'http://httpbin.org/post'
    >>> files = {'file': open('report.xls', 'rb')}
    >>> r = requests.post(url, files=files)