I have a sample curl command here to post a file to REST based API. my understanding is that, -F flag is used for multipart/form-data HTTP request and is required to upload a file(s).
curl -X POST -F "image=@/path/to/your/image" https://abc.example.com/v1/....
I have used python requests library to make HTTP calls as such , mostly a dictonary objects , serialized as json . essentially text data.
my question is how do i post a file , with python requests library? how does the HTTP call work with the files vs just sending text data as below? I'm learning web development so would help out with my understanding , how it works behind the scenes.
import requests
url = 'https://www.example.com/...'
data= {'key': 'value'}
x = requests.post(url, json = data)
print(x.text)
-F is indeed is a flag that is used for Form data. Your current code is sending data as JSON:
x = requests.post(url, json = data)
While you need to send files as multipart/form-data and argument that is used for this purpose is files
:
files = {"name": open('path/to/file','rb')}
x = requests.post(url, files=files)
As documentation states:
:param files: (optional) Dictionary of
'name': file-like-objects
(or{'name': file-tuple}
) for multipart encoding upload.file-tuple
can be a 2-tuple('filename', fileobj)
, 3-tuple('filename', fileobj, 'content_type')
or a 4-tuple('filename', fileobj, 'content_type', custom_headers)
, where'content_type'
is a string defining the content type of the given file andcustom_headers
a dict-like object containing additional headers to add for the file.