开发者

XML POST REST Request using Python

Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create New Project heading) shown here:

http://www.getharvest.com/api/projects

Here is the code I am trying to execute.

def postRequest():
    """ Makes POST request to url, and returns a response. """
    url = 'http://subdomain.harvestapp.com/projects'

    opener = urllib2.build_opener()
    opener.addheaders = [('Accept', 'application/xml'),
                        ('Content-Type', 'application/xml'),
                        ('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]), 
                        ('User-Agent', 'Python-urllib/2.6')]

    req = urllib2.Request(url=url, data=payload)
    assert req.get_method() == 'POST'
    response = self.opener.open(req)
    print response.code

    return response

I receive a response code 200 (Status OK) instead of a response code 201 (Created)...is this a question for the Harvest Support guys?

Any hints anyone h开发者_如何学运维as would be greatly appreciated.

Thanks, Jeff.


It's common to return a 200 response even when a 201 response would strictly be more appropriate. Are you sure that the request isn't correctly processed even if you are getting a 'correct' response?


You're using a local opener everywhere except on the line where you create the response, where you use self.opener, which looks like the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜