API调用在POSTMAN中工作,但生成代码的API调用不工作

6rqinv9w  于 2023-06-29  发布在  Postman
关注(0)|答案(3)|浏览(150)

API调用在Postman中工作,但当我使用生成的代码时,它不工作。
生成的代码:

import requests

url = "http://services.example.com/rest/v2/verification"

payload = "{\r\n  \"startDate\": \"2000-12-25\",\r\n  \"endDate\": \"2000-12-31\",\r\n  \"format\": \"CSV\"\r\n}"
headers = {
    'authorization': "Bearer XXXXX",
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "XXX"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

我已经尝试删除postman-token后执行,但仍然得到以下错误:

{"message":"Internal Server Error: correlationId=V2-ee8fb1b098490b8665dd936e8472978b","type":"error","code":1}
ukdjmx9f

ukdjmx9f1#

requests中使用传递json数据时,可以传递字典而不是字符串。
你可以试试这个:

import requests
import json

url = "http://services.XXX.com/rest/v2/verification"

payload = "{\r\n  \"startDate\": \"2000-12-25\",\r\n  \"endDate\": \"2000-12-31\",\r\n  \"format\": \"CSV\"\r\n}"
headers = {
    'authorization': "Bearer XXXXX",
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "XXX"
    }

response = requests.post(url,json=json.loads(payload),headers=headers)

print(response.text)
p8h8hvxi

p8h8hvxi2#

您可以通过以下方式将payload变量更改为Json对象:
而不是:

payload = "{\r\n  \"startDate\": \"2000-12-25\",\r\n  \"endDate\": \"2000-12-31\",\r\n  \"format\": \"CSV\"\r\n}"

您可以用途:

payload = {"startDate": "2000-12-25", "endDate": "2000-12-31",  "format":"CSV"}
iswrvxsc

iswrvxsc3#

这可能会有帮助dumps()函数将把Python对象的子集转换成json字符串。因此,您传入的不是Python列表,而是JSON

payload = json.dumps{"startDate": "2000-12-25", "endDate": "2000-12-31",  "format":"CSV"}

相关问题