使用请求将PHP API POST调用转换为Python
如何在Python中发出以下PHP API端点post请求:使用请求将PHP API POST调用转换为Python,php,python,api,post,python-requests,Php,Python,Api,Post,Python Requests,如何在Python中发出以下PHP API端点post请求: $cSession = curl_init(); $cFile = curl_file_create('my_receipt.jpg'); //Path to the file which will be uploaded $post = array('file_contents' => $cFile); curl_setopt($cSession, CURLOPT_URL, 'https://api.tabscanner.c
$cSession = curl_init();
$cFile = curl_file_create('my_receipt.jpg'); //Path to the file which will be uploaded
$post = array('file_contents' => $cFile);
curl_setopt($cSession, CURLOPT_URL, 'https://api.tabscanner.com/{your_api_key}/process');
curl_setopt($cSession, CURLOPT_POST, 1);
curl_setopt($cSession, CURLOPT_POSTFIELDS, $post);
curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cSession, CURLOPT_HEADER, false);
$result = curl_exec($cSession);
if (curl_errno($cSession)) {
$result = curl_error($cSession);
}
curl_close($cSession);
echo $result;
我尝试了以下方法:
import requests as rq
import json
import os
api_key = 'xxxx'
url = 'https://api.tabscanner.com/{}/process'.format(api_key)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) + '/'
img = PROJECT_ROOT + 'receipt1.jpg' # I presume this needs to be read as an image file, rather than just the filename
result = rq.post(url, data=json.dumps({'file': img}))
print(result.text)
这将导致以下输出:
{“message:“ERROR\u FORM\u PARSER:ERROR:missing content type header”,“status:“failed”,“status\u code:”4,“success:”false,“code:”406}
以下内容适合我
files = {'receiptImage': open(RECEIPT_FOLDER+'/receipt.jpg', 'rb')}
resp = requests.post(process_endpoint, files=files)
您错过了内容类型标题。如何将其添加到
请求中。尽管如此,post
调用中?另外,PHP示例将CURLOPT_HEADER
指定为false
,因此我假定它不接受头。我试过rq.post(url,headers={'file':img})
,rq.post(url,data=json.dumps({'file':img}),headers={})
,rq.post(url,data=json.dumps({'file':img}),headers=False)
,等等。这些都不起作用。你应该真正阅读错误消息和我链接的文档。我已经阅读了,无论我试图为标题参数包含什么,我都会收到与我原来问题相同的错误。我甚至查看了请求
源代码,看看是否添加了错误的标题。