如何使用Requests模块发起curl请求
我需要使用一个可以进行cURL调用的API。这个API的链接在这里:https://www.pivotaltracker.com/help/api/rest/v5。我在用Python 2.7编程,并且下载了Requests模块来进行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 /projects/{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 Watts) 现在这是我的代码:
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,
...
}
1 个回答
看起来你首先需要调用的是 '/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"
这指定了一个头部信息。对于 Requests,我们使用 headers
这个关键字参数 - headers={key:value}
。在这个具体的例子中,我们有 headers={'X-TrackerToken':token}
。
"https://..."
这是网址。它作为第一个参数传入。像 $PROJECT_ID
这样的变量可以通过字符串的 format
方法插入。