最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to post a file to an REST api via python - Stack Overflow

programmeradmin2浏览0评论

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" /....

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 = '/...'
data= {'key': 'value'}

x = requests.post(url, json = data)

print(x.text)

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/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/...'
data= {'key': 'value'}

x = requests.post(url, json = data)

print(x.text)
Share Improve this question asked Mar 13 at 2:21 no_reservationsno_reservations 91 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

-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 and custom_headers a dict-like object containing additional headers to add for the file.

发布评论

评论列表(0)

  1. 暂无评论