I am designing a REST service that could be used by many types of clients, most likely .Net, PHP, Flex and JavaScript. I am building the service using WCF and the REST starter kit. One of my main goals is to make it as simple as possible for all those clients to use the API.
Let’s say that the API deals with zoos. When the client creates a new zoo it would be nice if they could pass along the initial set of animals so they only need to make a single call to the API, e.g.
<Zoo>
<Name>My Zoo</Name>
<Animals>
<Snake>
<Name>Frank</Name>
<Length>2.5m</Name>
</Snake>
<Giraffe>
<Name>Alfred</Name>
<Height>10m</Height>
</Giraffe>
</Animals>
</Zoo>
I then want to deserialize the XML into C# classes like this:
List<Animal> Animals { get; set; }
class Animal { public string Name { get; set; } }
class Snake : Animal { public float Length { get; set; } }
class Giraffe : Animal { public float Height { get; set; } }
WCF doesn’t like this as it wants the XML formatted like this:
<Zoo xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>My Zoo</Name>
<Animals>
<Animal i:type="Snake">
<Name>Frank</Name>
<Length>2.5m</Name>
</Animal>
<Animal i:type="Giraffe">
<Name>Alfred</Name>
<Height>10m</Height>
</Animal>
</Animals>
</Zoo>
This looks like it is going to be trickier to work with in client without high end tooling support which raises lots of questions:
- Is there a better design for this API?
- Is the second format going to be a problem for non-WCF clients?
- Can I make WCF format this data the first way?
- Should I use these types of hierarchies in the XML at all?
Your question seems to be both about using WFC for REST and about modeling a concept in REST. I had an idea on your modeling question:
What about introducing a new resource to model the mass-import of animals? You might call it something like “Shipment”.
A Shipment might be defined as a list of new animals to be introduced into a Zoo. By exposing Shipment as a first-class resource, you would have the ability to manage them, track which Animal came in on which Shipment (to track down a disease outbreak, for example), and enable Shipments to take place at any time, not just during the creation of a Zoo.
Also, don’t forget that REST APIs must be hypertext-driven.