HTTP XML Post using Python

It’s basic stuff like this that always slips my mind when I need it. There are literally millions of ways to do this, but for me, this one is the most practical.

This should work on all Python versions (both 2.x and 3) and doesn’t use any nonstandard libraries. Of course, you don’t have to read XML from a file, you can easily modify the method to work with an XML string. In this example, I’m posting to an HTTP host. You could also easily modify this to work over HTTPS by using httplib.HTTPS as a webservice.

import sys, httplib

HOST = www.example.com
API_URL = /your/api/url

def do_request(xml_location):
	"""HTTP XML Post request, by www.forceflow.be"""
	request = open(xml_location,"r").read()
	webservice = httplib.HTTP(HOST)
	webservice.putrequest("POST", API_URL)
	webservice.putheader("Host", HOST)
	webservice.putheader("User-Agent","Python post")
	webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
	webservice.putheader("Content-length", "%d" % len(request))
	webservice.endheaders()
	webservice.send(request)
	statuscode, statusmessage, header = webservice.getreply()
	result = webservice.getfile().read()
        print statuscode, statusmessage, header
        print result

do_request("myfile.xml")

Leave a Reply