'How Do I Upload A File To As A multipart/form-data using requests Library?

I Want To Upload A File To A Remote Server Through REST API, using python requests Library. The Server Has Provided The Below Form.

<form enctype="multipart/form-data" action="https://m.youserver.com/upload/01" method="post">
<input type="hidden" name="api_key" value="apikey123">
<input name="file" type="file">
<input type="submit">
</form>

I tried uploading Using The following implementation. But Get A Custom Server Error Message That Is Not Useful At All.

import requests

key = "apikey123"
api = "https://m.youserver.com/upload/01"

files = {file: {'filename': open('file', 'rb')}}
r = requests.post(api, file=files)
print(r.text)

Maybe It has to do something with the hidden input(api_key), that im not providing. I tried Using Suggestions From Similar Problems Here on stackoverflow But That Didn't Solve the Problem.

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

key = "apikey123"
api = "https://m.youserver.com/upload/01"

m = MultipartEncoder(fields={'api_key': key, 'file': ('file', open('testvid.mp4', 'rb'), 'text/plain')})
r = requests.post(api, data=m, headers={'Content-Type': m.content_type})

This Is The Error I get:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 19, in <module>
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/models.py", line 917, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: [Errno Expecting value] <HTML><BODY><Form name='F1' action='https://streamsb.com/' target='_parent' method='POST'><textarea name="op">upload_result</textarea><textarea name="fn">file</textarea><textarea name="st">Not video file(file)</textarea></Form><Script>document.location='javascript:false';document.F1.submit();</Script></BODY></HTML>: 0

[Program finished]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source