[英]Python REST API call KO
我在調用 REST API 時遇到問題。
curl 調用工作正常:
curl -X POST "https://pss-api.prevyo.com/pss/api/v1/sentiments" -H "accept: application/json" -H "Content-Type: application/json" -H "Poa-Token: xxxxxx" -d "{\"text\": \"Paul n'aime pas la très bonne pomme de Marie.\"}
它也適用於 Postman。
但是我收到 Python request.post()
錯誤:
import requests
api_key_emvista = "xxxx"
def call_api_emvista():
try:
full_url = "https://pss-api.prevyo.com/pss/api/v1/meaningrepresentation"
headers = {"Poa-Token" : api_key_emvista,
"Content-Type" : "application/json",
"accept" : "application/json"}
data = {"text" : "Paul aime la très bonne pomme de Marie."}
response = requests.post(full_url, data=data, headers=headers) #, verify=False)
return response.json()
except Exception as e:
print(e)
response = call_api_emvista()
response
{'timestamp': 1614608564801,
'status': 400,
'error': 'Bad Request',
'message': '',
'path': '/pss/api/v1/meaningrepresentation'}
你有想法嗎?
如果您傳入一個字符串而不是dict
,則該數據將直接發布。
data = '{"text": "Paul aime la très bonne pomme de Marie."}'
除了自己編碼dict
,你也可以直接使用json
參數( 在 2.4.2 版本中添加)傳遞它,它將自動編碼。
def call_api_emvista():
try:
full_url = "https://pss-api.prevyo.com/pss/api/v1/meaningrepresentation"
headers = {
"Poa-Token": api_key_emvista,
"accept": "application/json",
}
data = {"text": "Paul aime la très bonne pomme de Marie."}
response = requests.post(
full_url, json=data, headers=headers
)
return response.json()
except Exception as e:
print(e)
請注意,如果傳遞data
或files
,則忽略json
參數。 在請求中使用json
參數會將 header 中的Content-Type
更改為application/json
。
根據您顯示的 curl 請求,您需要將您的令牌放入 header 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.