我需要使用一个进行cURL调用的API。这里显示的API:https://www.pivotaltracker.com/help/api/rest/v5。我正在用Python2.7编写代码,并下载了请求模块用于cURL调用,但我不太确定如何做到这一点。到目前为止,这就是我所拥有的:
import requests
username = 'my_username'
password = 'my_password'
url = 'https://www.pivotaltracker.com/n/projects/my_project_number'
r = requests.get(url, auth=(username, password))现在我有了响应r,如何使用它进行cURL调用,以便使用API函数,如GET /project_id/{project_id}/epics/{epic_id}函数。对此函数的cURL调用是:
export TOKEN='your Pivotal Tracker API token'
export PROJECT_ID=99
curl -X GET -H "X-TrackerToken: $TOKEN" "https://www.pivotaltracker.com/services/v5/projects/$PROJECT_ID/epics/4"谢谢你能提供的任何帮助!
编辑(感谢@Rob )现在这是我的代码:
import requests
username = 'my_username'
password = 'my_password'
url = 'https://www.pivotaltracker.com/services/v5/me'
r = requests.get(url, auth=(username, password))
response_json = r.json()
token = response_json['api_token']
project_id = 'my_project_id'
url = 'https://www.pivotaltracker.com/services/v5/projects/{}/epics/1'
r = requests.get(url.format(project_id), headers={'X-TrackerToken':token})
print r.text但还是不起作用。这是输出:
{
"code": "unfound_resource",
"kind": "error",
"error": "The object you tried to access could not be found. It may have been removed by another user, you may be using the ID of another object type, or you may be trying to access a sub-resource at the wrong point in a tree."
}但是根据文档,我希望这样的东西:
{
"created_at": "2014-08-26T12:00:00Z",
"description": "Identify the systems and eliminate the rebel scum.",
"id": 1,
...
}发布于 2014-09-11 22:04:29
应该进行的第一个调用似乎是对'/me‘端点的调用,然后从响应中提取API令牌:
import requests
username = 'my_username'
password = 'my_password'
url = 'https://www.pivotaltracker.com/services/v5/me'
r = requests.get(url, auth=(username, password))
response_json = r.json()
token = response_json['api_token']除了您的API令牌之外,您还可以从该端点获得一些其他内容。看看该端点的文档,看看是否还有什么需要的。
一旦您获得了API令牌,所有其他调用都将相当简单。例如:
project_id = 'your_project_id' # could get this from the previous response
r = requests.get('https://www.pivotaltracker.com/services/v5/projects/{}/epics/4'.format(project_id), headers={'X-TrackerToken':token})我将解释本例中cURL调用的各个部分,以及它们是如何转换的:
export VARNAME为cURL调用设置一个要使用的变量。在您看到的地方,$VARNAME是使用变量的地方。
-X GET我不知道他们为什么包括这个。这只是指定使用GET,这是cURL的默认设置。使用requests.get可以解决这个问题。但是,对于那些有-X POST的用户,您可以使用requests.post等等。
-H "X-TrackerToken: $TOKEN"这指定了一个标头。对于请求,我们使用headers关键字参数- headers={key:value}。在这个具体的例子中,我们有headers={'X-TrackerToken':token}。
"https://..."那个网址。这是第一个论点。变量(如示例中的$PROJECT_ID )可以使用字符串的format方法插入。
https://stackoverflow.com/questions/25797455
复制相似问题