The wonder of conventions: CXF REST services get easier
December 3rd, 2006One of the things I hear often from the Ruby fan boys and girls is the wonders of conventions. A while back I posted a bit on CXF’s new found REST support using annotations. But, given any class which does CRUD operations, there are a lot of similarities, so shouldn’t we be able to employ some conventions as well?. The latest code in CXF’s SVN takes a cue from the Ruby community and knows how to turn CRUD operations into resources automatically.
Its a bit hard to write the rules in narrative form, so I’ll stick to examples. Rest assured though, its documented in the javadoc and soon to be in the user’s guide (no pun intended).
Example 1: Collection<Person> getPeople() is mapped to an HTTP GET on /people
That’s straightforward enough. We see “get”, we map it to a GET operation. Then people is extracted from the operation name and turned into a simple URI.
Example 2: Person getPerson(id) is mapped to an HTTP GET on /people/{id}.
Here we’re again extracting a resource name from the operation, but you’ll notice we’re pluralizing it. When I said taking a cue from Ruby, I meant it literally. I ported Ruby’s ActiveSupport inflection code to Java. It is able to take most English words and pluralize them. Pluralizing “person” to “people” becomes as easy as new EnglishInflector().pluralizer(”person”). You can also add your own singular to plural mappings if it isn’t covered.
All the parameters from the operation get appended to the resource name. If there were two parameters, “bit” and “bob” it would become /people/{bit}/{bob}. CXF will only map bit and bob though if they’re XML schema primitives (int, string, dateTime, etc).
Example 3: void addPerson(Person person) is mapped to an HTTP POST on /people.
We’re recognizing the “add” here as a “POST” operation. “create” is also acceptable. And again some pluralizer magic to map the add to /people.
Example 4: void updatePerson(long id, Person person) is mapped to an HTTP PUT on /people/{id}.
The same rules here as #2 except we’re mapping “update” operations to PUTs.
Example 5: void deletePerson(long id) is mapped to an HTTP DELETE on /people/{id}
The same rules here as #2 and #4 except we’re looking for “delete” and “remove” in the operation and mapping it to an HTTP DELETE.
While this isn’t revolutionary by any means, I think its a nice simple step to make the creation of REST style HTTP services easier. I hope it will enable more in the future.
P.S. if you are looking for a Java pluralizer, be sure to check out the one in CXF’s SVN. This whole thing would’ve taken about 10 minutes if I had it around before.
December 4th, 2006 at 12:14 am
CXF REST Conventions
Dan Diephouse: The latest code in CXF’s SVN takes a cue from the Ruby community and knows how to turn CRUD operations into resources automatically. Examples: Selection: Collection getPeople() is mapped to an HTTP GET on /people Person getPerson(i…