使用请求将PHP API POST调用转换为Python

时间:2019-03-06 10:26:47

标签: php python api post python-requests

我该如何在Python中发出以下PHP API端点发布请求:

$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_FORM_PARSER: Error: missing content-type header","status":"failed","status_code":4,"success":false,"code":406}

1 个答案:

答案 0 :(得分:0)

以下为我工作

files = {'receiptImage': open(RECEIPT_FOLDER+'/receipt.jpg', 'rb')}
resp = requests.post(process_endpoint, files=files)