0

I am new to RESTful services and their implementation on Spring 3. I would like your opinion on the best practices for returning type when a client creates a new resource in my server.

@RequestMapping(method = RequestMethod.POST, 
value = "/organisation", 
headers = "content-type=application/xml")
@ResponseStatus(HttpStatus.CREATED)
public ??? createOrganisation(@RequestBody String xml) 
{
    StreamSource source = new StreamSource(new StringReader(xml));
    Organisation organisation = (Organisation) castorMarshaller.unmarshal(source);
    // save 
    return ???;
}

3 Answers3

0

A simple choice would be javax.ws.rs.core.Response, found in the Java EE's own restful services package. It - simply - tells what the web server should answer to the HTTP request. For instance:

if (organisation != null)
  return Response.ok().build();
else
  return Response.serverError().build();

Custom response headers and other exotic things like that are possible with that return type too, but I don't think that would match with "best practices".


uh, I missed that @ResponseStatus(HttpStatus.CREATED)... I guess my answer was not much of help.

Maybe this will help instead: How to return generated ID in RESTful POST?

Community
  • 1
  • 1
Hannes R.
  • 1,379
  • 16
  • 23
  • This one will help http://stackoverflow.com/questions/12837907/what-to-return-if-spring-mvc-controller-method-doesnt-return-value – Xiangyu Aug 24 '15 at 09:35
0

It is a good idea to return the newly created entity(with the generated id) wrapped in ResponseEntity. You can also set the HttpStatus in ResponseEntity based on the result of the operation.

     @RequestMapping(method = RequestMethod.POST, 
         value   = "/organization", 
         headers = "content-type=application/xml")
     public ResponseEntity<Organization> createOrganisation(@RequestBody String xml) {
            StreamSource source = new StreamSource(new StringReader(xml));
            Organization organisation = (Organization) castorMarshaller.unmarshal(source);
            // save 
            return new ResponseEntity<Organization>(organization, HttpStatus.OK);
        }
FFL
  • 669
  • 7
  • 22
0

I would go for a ResponseEntity<byte[]> and you would have take care of the marshalling of your response on your controller method. Notice that you are basically scrapping the V in MVC, there is a MarshallingView on Spring but from experience I consider the previous solution much more flexible and easier to understand.

ilcavero
  • 3,012
  • 1
  • 31
  • 27