使用REQUESTS / Shiftplanning API的Python Post请求

问题描述 投票:0回答:1

我试图用以下代码调用shiftplanning API:

import requests
url= "https://humanity.com/api/"
payload = {"key": "keyvalue",  "request": {    "module": "staff.login", "method": "GET","username": "myusername", "password": "mypassword"}}"
headers = {
    'content-type': "application/x-www-form-urlencoded",
    'cache-control': "no-cache",
    } 
r = requests.post(url, data = payload
, headers= headers) 
r.text

我使用Postman预先测试api,它工作正常。但是,Postman代码创建器中的有效负载如下所示:

payload = "data={\r\n  \"key\": \"keyvalue\",\r\n  \"request\": {\r\n    \"module\": \"staff.login\",\r\n    \"method\": \"GET\",\r\n    \"username\": \"myusername\",\r\n    \"password\": \mypassword\"\r\n  }\r\n}"

我假设,有效负载变量实际上需要格式化为字符串,因为shiftplanning api中的doc说:

请记住,传递给API的任何数据都要格式化为JSON,并且其字符串值需要通过POST HTTP请求方法发送,作为post变量'data'(从下面的示例中查看第9行)。 Content-Type也需要设置为application / x-www-form-urlencoded。

但是,无论我做什么,我总是得到api的html作为返回,而不是json对我的http请求的响应。运用

r.json()

由于返回的html,除了引发错误之外没有做任何事情。我也试过用

json = payload

在帖子请求中,这也没有改变任何东西

任何帮助和解释表示赞赏。我真的很想了解我做错了什么,因为执行它似乎非常简单。

python post python-requests
1个回答
0
投票

如果你想要json响应,请将content-type中的headers更改为application/json。 Postman会自动为您设置该标题,但您需要在Python代码中设置它。

© www.soinside.com 2019 - 2024. All rights reserved.