REST - Returning Created Object with Spring MVC

From the HTTP specification for POST:

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).

What you will return in the response body will depend on how strictly you interpret an entity which describes the status of the request and refers to the new resource - and many implementations simply return a representation of the newly created entity itself. The most important thing is to set the Location header in the response to be the URI of the newly created resource, so that clients may immediately fetch it if they so choose.


Try using ResponseEntity which returns HTTP status along with the object you need.

Sample code is (this was my code where I am returning Customer object, change it as per your needs) :

// imports (for your reference)
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

// spring controller method
@RequestMapping(value = "getcust/{custid}", method = RequestMethod.GET, produces={"application/json"})
public ResponseEntity<Customer> getToken(@PathVariable("custid") final String custid, HttpServletRequest request) {

    customer = service.getCustById(custid);

    return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}

Read this documentation to know more. Some sample code has been provided there.