首页 > 解决方案 > 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'}

你有想法吗?

标签: pythonpython-requests

解决方案


如果您传入一个字符串而不是 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则忽略该参数。在请求中使用参数会将标头中的 更改为.datafilesjsonContent-Typeapplication/json


推荐阅读