Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML POST with Python Requests

I'm trying to use the uClassify API to categorize objects based on a text. To interact with the API, I need to make XML POST requests, such as:

<?xml version="1.0" encoding="utf-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/RequestSchema" version="1.01">
  <writeCalls writeApiKey="YOUR_WRITE_API_KEY_HERE" classifierName="ManOrWoman">
    <create id="CreateManOrWoman"/>
  </writeCalls>
</uclassify>

I tried to do this using the HTTP Requests module as well as xml.etree.ElementTree to create an XML tree, but I am getting errors left and right. Here's some code I tried:

>>> import elementtree.ElementTree as ET
>>> from xml.etree.cElementTree import Element, ElementTree
>>> import requests
>>>
>>> root = ET.Element("uclassify", xlms="http://api.uclassify.com/1/RequestSchema", version="1.01")
>>> head = ET.SubElement(root, "writeCalls", writeApiKey="*************", classifierName="test")
>>> action = ET.SubElement(head, "create", id="CreateTest")
>>> tree = ElementTree(root)
>>>
>>> r = requests.post('http://api.uclassify.com/', tree)
>>> 
>>> ........
>>> TypeError: must be convertible to a buffer, not ElementTree
like image 991
bmay2 Avatar asked Dec 26 '22 20:12

bmay2


2 Answers

Once, when I had to do a similar thing, I did like this:

requests.post(url, data=xml_string, headers={'Content-Type':'application/xml; charset=UTF-8'})
like image 183
JOHN_16 Avatar answered Dec 29 '22 11:12

JOHN_16


Not a requests method, but here's a real simple recipe using urllib2 from my codebase:

import urllib2

from elementtree import ElementTree

def post(url, data, contenttype):
    request = urllib2.Request(url, data)
    request.add_header('Content-Type', contenttype)
    response = urllib2.urlopen(request)
    return response.read()

def postxml(url, elem):
    data = ElementTree.tostring(elem, encoding='UTF-8')
    return post(url, data, 'text/xml')

I suspect what you're missing is the use of tostring to convert the ElementTree Element that you named root.

like image 45
zigg Avatar answered Dec 29 '22 12:12

zigg