Fun with Groovy and RESTClient
So I have finished up the basic API for our user management system in grails so it is now time to switch gears and start working on the client. I decided to go with groovy (hey I need to hone in my skills =P) so I went off to find out how other people were attaching onto RESTful apis. Well it seems that most people are using the RESTClient found in the HTTPBuilder library. It has WAY more dependencies than I would like to have but I will worry about that later. Here is the first consuming method I have written using the client.
1 2 3 4 5 6 7 8 9 10 11 12 13 | def static list(appId, accessTypeCode) { def accessLevels = [] def client = new RESTClient("http://localhost:8080/AppHub/accessLevel/${appId}/${accessTypeCode}") def resp = client.get(contentType:ContentType.XML, query:[format:'xml']) resp.data.children().each { list -> def accessLevel = new AccessLevel() list.children().each { child -> accessLevel.setProperty(child.name, child.text()) } accessLevels.add(accessLevel) } return accessLevels } |
1 | println AccessLevel.list('LEGALDOC', 'ACCESS_LVL').size() |
Pretty straight forward and the code is much shorter than it would be in Java (or heck even in Groovy) if I needed to manually setup all of the HTTP/URL connection and parse the response back.
Notice that I am using some metaprogramming to dynamically build AccessLevel objects from the responding XML. This works for this particular example and will continue to work for most of the API. However, if I ever return a deeper xml tree (User -> List of some object -> object) It will take a bit more finesse.
Leave a comment
You must be logged in to post a comment.

