how to use python's Request library to make an API call with an attachment and a parameter

风格不统一 提交于 2019-12-13 03:39:42

问题


I am using the Request library to test ReST APIs. I am facing a problem while trying to trasform the below cURL to request library Call.

curl https://upload.box.com/api/2.0/files/content \ -H "Authorization: Bearer ACCESS_TOKEN" \ -F filename=@FILE_NAME \ -F parent_id=PARENT_FOLDER_ID

I tried many of the suggestions in this forum. But nothing worked.

The code which I addedd after the comment is:

The code I wrote was:

def upload_a_file(url, folder_id, file_name, access_token): field_values = "{\'filename\': (filename, open("+file_name+", \'rb\'))}" payload = "{\'parent_id\':"+folder_id+"}" request_headers = {'Authorization': 'Bearer '+access_token} result = requests.post(url, headers=request_headers, data=payload, files=field_values) response = result.json() print response


回答1:


I assume you mean the requests library?

If so, here is how I do it.

access_token = <user access token>
filename = <name of the file as you want it to appear on Box>
src_file = the actual file path
parent_id = the id of the folder you want to upload to

headers = { 'Authorization' : 'Bearer {0}'.format(access_token) }
url = 'https://upload.box.com/api/2.0/files/content'
files = { 'filename': (filename, open(src_file,'rb')) }
data = { "parent_id": parent_id }
response = requests.post(url, data=data, files=files, headers=headers)
file_info = response.json()



回答2:


I followed the example given in http://www.snip2code.com/Snippet/67408/Show-progress-bar-when-uploading-a-file.

I was able to make a successful API call.



来源:https://stackoverflow.com/questions/25942163/how-to-use-pythons-request-library-to-make-an-api-call-with-an-attachment-and-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!