使用Python访问简单的API

时间:2013-01-31 11:52:22

标签: python api curl urllib2 pycurl

我有一个简单的api端点:

http://example.de/create.json

我需要通过POST发送以下内容:

-text

-url

-username

此任务的curl命令如下所示:

curl --data-urlencode "text=Beispieltext" -d "url=http://google.de" -d "username=User1" http://example.de/create.json

我想在我的代码中实现这一点。我想向api提交数据并使用api的答案。 其实我不知道从哪里开始。我阅读并尝试了很多关于Pycurl,urllib2和subprocess的内容,但现在我对此一无所知:D

你会怎么做? 我需要帮助,我不知道从哪里开始!

2 个答案:

答案 0 :(得分:1)

非常简单。应该是这样的:

import pycurl
import StringIO

c = pycurl.Curl()
c.setopt(c.URL, 'http://example.de/create.json')
output = StringIO.StringIO()
c.setopt(c.WRITEFUNCTION, output.write)
c.setopt(c.POSTFIELDS, 'your post data')
c.perform()

结果在output.getvalue()中。完成后不要忘记输出.close()。

答案 1 :(得分:0)

libcurl Examples(参见右栏中的那些)