请求包和 API 文档

Requests package and API documentation

我无法理解在何处添加 API 文档定义的参数。以BeeBole的documentation为例,它指定通过ID获取缺席,需要以下请求:

    {
"service": "absence.get",
"id": "absence_id"
}

他们在文档中只提供了一个URL:

BeeBole is accepting HTTP POST resquests in a json-doc format to the following URL: https://beebole-apps.com/api/v2

这将如何在 Python 请求的上下文中实施?以下代码我试过 returns 404:

import requests

payload = {
    "service": "absence.get",
    "id": "absence_id"
}

auth = {
    "username": "API_token",
    "password": "x"
}

url = "https://beebole-apps.com/api/v2"

req = requests.get(url, params=payload, auth=auth).json()

BeeBole is accepting HTTP POST resquests in a json-doc format to the following URL: https://beebole-apps.com/api/v2

这里的JSON文档格式是你漏掉的部分;您需要将信息作为请求的 JSON 编码 body 传递。您使用的 params 参数仅设置 URL 查询字符串(URL 中的 ?... 部分)。

使用

import requests

payload = {
    "service": "absence.get",
    "id": "absence_id"
}

auth = ("API_token", "x")    
url = "https://beebole-apps.com/api/v2"

req = requests.get(url, json=payload, auth=auth).json()

json= 部分确保 payload 字典被编码为 JSON 并作为 POST body 发送。这也设置了请求的 Content-Type header。

我也更新了 API authentication, all that the auth keyword needs here is a tuple of the username and password. See the Basic Authentication section

您可能需要等待调用 .json() 响应;先检查是否响应成功:

req = requests.get(url, json=payload, auth=auth)
if not req.ok:
    print('Request not OK, status:', req.status_code, req.reason)
    if req.content:
        print(req.text)
else:
    data = req.json()
    if data['status'] == 'error':
        print('Request error:', data['message'])

这使用了 documented error responses.

从站点文档可以看出,该特定供应商选择了一个不寻常的 API。大多数人使用不同的端点来实现不同的操作,但 BeeBole 似乎是在同一个端点上实现所有操作,然后通过检查请求数据中的 "service" 键来选择操作。

尝试

response - request.post('https://beebole-apps.com/api/v2',
                        json={"service": "company.list"},
                        headers={"authorization": TOKEN)

从文档中我不能保证将以正确的格式提出请求,但至少如果它不起作用,它应该为您提供一些关于如何继续的线索。 BeeBole 文档中的 "Authorization" 中描述了 TOKEN 的正确值。

这是一种提供 API 的不寻常方式,但它似乎可行。