i am trying to convert a curl method into a python POST
request.
Here is the curl command:
curl --location --request POST 'https://global.kaleyra.com/api/v4/' --form 'file=@/home/user/Desktop/TWP_MD565041.pdf' --form 'method=wa' --form 'api_key=A3d51xxxxxxxxxxxxxxxxxxxxxxxxxx' --form 'from=971xxxxxxxxxx' --form 'body={
"to":"9198xxxxxxxx",
"type": "document", "document" : {"caption" : ""},
"callback":""
}' --form 'format=json'
And here is the python request ia tried:
payload = {
"method": "wa",
"api_key": "A3dxxxxxxxxxxxxxxxx",
"body": '{"to":'+str(user_number)+',"type": "document"}',
'from': '971xxxxxxxx',
'format':'json',
"file":open("/home/user/Desktop/TWP_MD565041.pdf","rb")}
r = requests.post(url=api_url,headers={}, files=payload)
getting error:
b'{"status":"A401B","message":"Method Not Found"}'
Then i changed request like this:
r = requests.post(url=api_url,headers={}, files=json.dumps(payload))
Now am getting an error:
TypeError: Object of type 'BufferedReader' is not JSON serializable
And i tried this,
with open("/home/user/Desktop/TWP_MD565041.pdf",'rb') as f:
r = session.post(url=api_url,headers=headers, data=json.dumps(payload),files={"file":f})
Then i an getting an error:
ValueError: Data must not be a string.
How can i resolve this?
1) Requests will serialize the JSON for you. Drop the json.dumps method and use the raw payload.
2) I suggest sending the file as such. The with statement is used for larger atomic manipulations, and you really don't need to keep the file open while performing API I/O. Therefore, use the following method, as the file stream is implicitly closed after interpretation.
r = session.post(
url = api_url,
headers = headers,
data = payload,
files = {'file': open('file.pdf','rb')}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.