5

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.

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.