简体   繁体   中英

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 has 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?

除了在你创建响应的行上,你使用的是本地开启者,你在那里使用self.opener ,这看起来像是问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM