Categories

Django REST models

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

  1. <address id="123" num="3301">
  2.   <street>8th Street</street>
  3.   <city>Saskatoon</city>
  4.   <province>SK</province>
  5.   <country>Canada</country>
  6. </address>

The model might be defined as

  1. class Address(xml_models.Model):
  2.   id = xml_models.IntField(xpath="/address/@id")
  3.   num = xml_models.IntField(xpath="/address/@num")
  4.   street = xml_models.CharField(xpath="/address/street")
  5.   city = xml_models.CharField(xpath="/address/city")
  6.   province = xml_models.CharField(xpath="/address/province")
  7.   country = xml_models.CharField(xpath="/address/country")
  8.  
  9.   finders = { (id,): "http://myaddressbook.com/addresses/%s" ,
  10.                     (num,street): "http://myaddressbook.com/addresses/num/%s/street/%s"}
  11.  

And using the finder method would be like this

  1. 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.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>