Making external XML REST apis more pythonic
At work we have a Django web application where the models are backed by a Java XML REST api. The application is read only, so there is no requirement to write back to the REST api.
We started with copying the data into a local DB, and using regular Django DB models, and we wanted something that would feel very similar, but use an XML REST backend. We wrote an xml_models library, which allowed us to map our models to the XML data, using a declarative style similar to the Django DB models. The library has been open sourced and can be found on sourceforge.
Here is a simple example:-
Suppose there was an API http://myaddressbook.com/addresses/{addressID} that returns the following XML
-
<address id="123" num="3301">
-
<street>8th Street</street>
-
<city>Saskatoon</city>
-
<province>SK</province>
-
<country>Canada</country>
-
</address>
The model might be defined as
-
class Address(xml_models.Model):
-
id = xml_models.IntField(xpath="/address/@id")
-
num = xml_models.IntField(xpath="/address/@num")
-
street = xml_models.CharField(xpath="/address/street")
-
city = xml_models.CharField(xpath="/address/city")
-
province = xml_models.CharField(xpath="/address/province")
-
country = xml_models.CharField(xpath="/address/country")
-
-
finders = { (id,): "http://myaddressbook.com/addresses/%s" ,
-
(num,street): "http://myaddressbook.com/addresses/num/%s/street/%s"}
-
And using the finder method would be like this
-
address = Address.objects.get(id=123)
That’s the basics. We are mapping much more complex relationships with collection fields, date fields and more. Take a look and let me know what you think.
