如何使用Requests Python模块进行curl调用

时间:2014-09-11 21:45:39

标签: python python-2.7 curl python-requests pivotaltracker

我需要使用一个进行cURL调用的API。此处显示的API:https://www.pivotaltracker.com/help/api/rest/v5。我在Python 2.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 / 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 个答案:

答案 0 :(得分:5)

看起来您应该首先调用'/ 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令牌之外,您还可以获得其他一些东西。看看the documentation for that endpoint,看看是否还有其他需要。

获得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)。