python - Python REST API 调用 KO
问题描述
我在调用 REST API 时遇到问题。
卷曲调用工作正常:
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.\"}
它也适用于邮递员。
但是我得到了一个 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'}
你有想法吗?
解决方案
如果您传入一个字符串而不是 a 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)
请注意,如果传递了或,json
则忽略该参数。在请求中使用参数会将标头中的 更改为.data
files
json
Content-Type
application/json
推荐阅读
- java - MediaPlayer 是否仅播放具有比特率模式的 mp3 文件:变量?
- javascript - 制作密码搜索空间计算器 & 需要帮助创建一个基于 html 中 (java) 中的变量创建递归的函数
- java - 线程“主”org.apache.spark.sql.AnalysisException 中的异常:无法解析列
- jekyll - 在 Jekyll 中按姓氏排序
- dart - 飞镖角度与调试
- javascript - 将 addEventListener 添加到所有按钮
- reactjs - 为什么我无法从 react-router 获取参数?
- elasticsearch - 为什么 ElasticSearch 有时不显示 Logstash 发送的最新日志?
- java - 如何检查 ClassType 是否继承自 JDI 中的 java.util.Collection?
- c# - 在空中跳跃时如何保持动力?