Starter Project to build RESTful API’s with SpringMVC

While SpringMVC makes it quite easy to create RESTful services, this starter project adds a few things more. It provides a consistent way to send error messages in json back to the caller and also integrates Spring Security into the mix.

With Spring its as easy as registering a regular bean, annotating it with a few annotations, returning a POJO and the framework will convert the response to an appropriate output format. In my case I am interested in XML and JSON. To register support for JSON simply add the jackson libraries to the project. JAXB2 is part of JDK 1.7 so there are no additional jars to include. I did include both converters to the context xml.

	<mvc:annotation-driven
		content-negotiation-manager="contentNegotiationManager">
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
			<bean
				class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
		</mvc:message-converters>
	</mvc:annotation-driven>

 

To run the application…

First clone it from GitHub – https://github.com/thomasma/springmvc-restful

mvn clean package

mvn jetty:run

To access the RESTful Services…(with JSON Responses)

  • Retrieve all Notes:
    • curl -XGET -H “Accept: application/json” –user admin:password http://localhost:8080/service/note/notes
  • Retrieve Single notes:
    • curl -XGET -H “Accept: application/json” –user admin:password http://localhost:8080/service/note/{replacethiswithanid}
  • Add New Note:
    • curl -XPOST -H “Content-Type: application/json” -H “Accept: application/json” –user admin:password http://localhost:8080/service/note -d ‘{“message”:”hello there”}’
  • Field validation errors from REST service:
    • curl -XPOST -H “Content-Type: application/json” -H “Accept: application/json” –user admin:password http://localhost:8080/service/note -d ‘{}’
  • Single simple error messages from REST service:
    • curl -XGET -H “Accept: application/json” –user admin:password http://localhost:8080/service/note/error1
  • Multiple error messages from REST service:
    • curl -XGET -H “Accept: application/json” –user admin:password http://localhost:8080/service/note/error2

To Get XML Responses…(with XML Responses)

Either replace HTTP Header with application/json with application/xml OR append .xml (or .json) extension to the URI. Example…

  • curl -XGET -H “Accept: application/xml” –user admin:password http://localhost:8080/service/note/notes
  • curl -XGET –user admin:password http://localhost:8080/service/note/notes.xml