Request a POST REST XML 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 python urllib2 library to "create a new project" in the crop API, with no luck. The payload variable is a valid XML document that is located next to the copy / paste of their documentation (under the heading "Create a new project"), shown here:

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

Here is the code I'm 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 get a 200 response code (OK status) instead of 201 response code (created) ... is this a question for the crop support guys?

Any hints that anyone would be very grateful.

Thanks, Jeff.

+5
2

, 200, 201 . , , "" ?

+1

, , , self.opener, .

+1

All Articles