繁体   English   中英

我想将文件作为附件发送到 API POST 请求

[英]I want to send file as attachment to an API POST request

我正在尝试在 POST 请求naturalHR API中为候选人发送文件:我已经尝试使用POSTMAN进行相同的请求,并且效果很好。 但是当我尝试使用 python 来集成 API 的POST请求以附加文件时,我收到一个错误,它的cv参数应该是一个文件(它的 API 错误响应)。

源代码:

from pprint import pprint
import json
import requests
import urllib.request
headers = {
    'accept': 'application/json',
    'Authorization': api_key,
    'Host': 'api02.naturalhr.net',
    'Referer': 'https://api02.naturalhr.net/api/documentation',
    'Content-type': 'multipart/form-data',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}
payLoad = dict()
payLoad["firstname"] = json_of_vals['firstname']
payLoad["surname"] = json_of_vals['surname']
payLoad["email"] = json_of_vals['email']
payLoad["cv"] = "Path/To/PDF_File"
files = {'file': "outfilename.pdf"}
api_url = "https://api02.naturalhr.net/api/v1/candidate"
res = requests.post(api_url, files=files, headers=headers, data=request_data)
print(res.content)

请不要将此标记为与此处已回答的问题的重复,因为我已经通过使用文件作为请求的参数对其进行了测试,例如:

res = requests.post(api_url, files=files, headers=headers, data=request_data)

编辑:我尝试过的答案:

在单个请求中使用 Python 请求发送文件和 JSON

我正在添加一个 header

'accept': 'application/json'

不应该在那里,我只使用用户代理API 密钥进行了尝试,它根据要求工作得非常好。

更正的代码:

from pprint import pprint
import json
import requests
import urllib.request
headers = {
    'Authorization': api_key,
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
}
payLoad = dict()
payLoad["firstname"] = json_of_vals['firstname']
payLoad["surname"] = json_of_vals['surname']
payLoad["email"] = json_of_vals['email']

files = {'file': "PATH/TO/FILE/FROM/LOCAL/DRIVE"}

api_url = "https://api02.naturalhr.net/api/v1/candidate"
res = requests.post(api_url, headers=headers, data=payLoad, files=files)
print("Status Code is: ", res.status_code)
print("Returned JSON Response is:\n")
pprint(res.text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM