Tuesday, March 29, 2011

0 to RestFul Resource in 17seconds.

Lets see some rails people figure out how to do this as dead simply as in spring-roo on java.

spring-roo commands:

mkdir myrestful_resource
cd myrestful_resource
project --topLevelPackage com.my.web.my.restful.resources
persistence setup --provider HIBERNATE --database HYPERSONIC_IN_MEMORY
entity --class ~.domain.Resource1
field string --fieldName myfirstfield
field string --fieldName mysecondfield
controller all --package ~.controllers
osgi start --url http://spring-roo-addons.googlecode.com/files/net.tzolov.httprepresentations.roo.addon-1.1.7.jar
http resource representation setup
http resource add oxm --class ~.domain.Resource1

json/html conversion works out of the box without modification however you need to annotate the model objects you want converted to xml by jaxb with @XmlRootElement so it knows what you want returned.

vi src/main/java/com/my/web/my/restful/resources/domain/Resource1.java

mvn tomcat:run

open up http://localhost:8080/resources in your browser and create some data on the auto-generated controllers.

access it via your browser or curl by simply appending .json .xml extensions to the url.

curl http://localhost:8080/resources/resource1s/1.json
curl http://localhost:8080/resources/resource1s/1.xml
curl http://localhost:8080/resources/resource1s/1.html


also check out this springsource post about hitting json rest based services with curl.


  1. if all you need is json, you could also simply issue the "json all" spring roo command.
    Then access the service with the appropriate header like so.

    curl -i -H Accept:application/json http://localhost:8080/resources/resource1s/1

  2. also works for HTTP POST
    curl -i -H "Accept:application/json" -H "Content-type: application/json" -X POST -d '{your json here}' http://localhost:8080/resources/resource1s