我在调用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'}
你有想法吗?
如果您输入的是字符串而不是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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句