简体   繁体   中英

REST - Returning Created Object with Spring MVC

I have a REST call that accepts a JSON object, lets say, a person. After I create this object (validated and saved to the database), I need to return the newly created JSON Object.

I think the standard practice is to return 201 Accepted instead of returning the object immediately. But my application needs the newly created object immediately.

I have a controller methods that take a POST call, calls a service class, which in turn calls a DAO that uses Hibernate to create the object. Once it's saved to the database, I am calling another controller method that takes the ID of the person and returns the Object.

My question, is this the better approach? ie, calling another Controller method to get the newly created object. Or the POST call itself should return the Object.

The main question is: Calling another method takes a round trip and I guess it's an overkill. (Service->DAO->Hibernate->Database). Instead I think I should get the Object from the database immediately after it's saved in the same call (from the method that handled POST).

What is the architecture standard here?

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.

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.

您可以在使用@ResponseBody 持久化实体对象后立即返回实体对象,在@ResponseStatus 之后,但它不是标准的,因此您的客户必须了解此自定义,否则如果您的客户依赖于标准 API,您必须坚持标准通过返回无效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM