View RSS Feed

Spring Framework

RESTful POST Method in Spring

Rate this Entry
by , 11-28-2011 at 01:02 AM (5215 Views)
In my previous tips, I have shown you how to write RESTful methods for GET, PUT and DELETE. In this tip, I will tackle the method which is probably the most used (and abused), the POST method.

The POST method is the one method that you need to be most mindful of. First it is not safe and second it is not idempotent. Therefore you must take extra care in how you design your URL as well as your method . In this case, I will add another method to the CarController that creates a new Car resource:

Java Code:
@RequestMapping(method=RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) 
public @ResponseBody Spittle createSpittle(@Valid Car car,
			BindingResult result, HttpServletResponse response)
			throws BindException { if(result.hasErrors()) {
	if(result.hasErrors()) {
	throw new BindException(result);
	}
	carService.saveCar(car);
	response.setHeader("Location", "/car/" + car.getId());
	return car;
}
Notice that the @RequestMapping annotation is different from GET, PUT and DELETE. It has no value attribute. So the @RequestMapping is responsible for determining the URL pattern handled by createCar(). In fact itís createCar that will handle the requests whose URL pattern matches /cars. The interesting thing here is that as we are creating a new resource, we cannot know the URL beforehand. Therefore POST has to operate against the URL that will be different every time. Finally the @ResponseStatus is set to the HTTP status code of the request. If you know your HTTP Responses, you will know that if successful this will return status 201(created). This doesnít preclude you return the entire resource representation once it is created. Also the method createCar will set the Location header with the URL for the new resource.

Now that we know the key methods used, I will look at another issue of RESTful service. In both createCar and getCar, an entire representation of the car will be returned in the body of the response. The question is how will this method be transformed into a representation that is useful to the client. I will look at this in the next tip.

Submit "RESTful POST Method in Spring" to Facebook Submit "RESTful POST Method in Spring" to Digg Submit "RESTful POST Method in Spring" to del.icio.us Submit "RESTful POST Method in Spring" to StumbleUpon Submit "RESTful POST Method in Spring" to Google

Updated 11-30-2011 at 01:41 PM by Spring Framework

Categories
REST , HTTP

Comments