Categories
Python Answers

How to upload a file with the Python requests module?

Spread the love

Sometimes, we want to upload a file with the Python requests module.

In this article, we’ll look at how to upload a file with the Python requests module.

How to upload a file with the Python requests module?

To upload a file with the Python requests module, we can call requests.post with the URL of the endpoint to upload the file to and set the files parameter to a dictionary with the form data payload.

For instance, we write:

import requests

url = 'http://httpbin.org/post'
files = {'file': open('file.csv', 'rb')}

r = requests.post(url, files=files)
print(r.text)

We call requests.post with the url and files set to the files dictionary.

We set the file form data entry to the file handle of the file.csv file.

Then we get the response text with r.text.

Conclusion

To upload a file with the Python requests module, we can call requests.post with the URL of the endpoint to upload the file to and set the files parameter to a dictionary with the form data payload.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *