Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What a RestController method should return when I insert a brand new object in the system? The inserted object or a message?

I am working on a Spring Boot project implementing some REST API and I am asking what is the best output of a controller method that insert a brand new object into the system (call a service method saving the object into the DB). In the project on which I am working on I am finding two different return styles (my idea is to do some refactoring bringing to a single return type). So Basically I have these two controller method return styles:

1) The controller return the inserted object as JSON repsonse payload, something like this:

@ApiOperation(
          value = "Insert a new wallet into the system", 
          notes = "A wallet can be assigned to a specific user or to no-one. It will be assigned in a second time",
          produces = "application/json")
@PostMapping(value = "/admin/wallet", produces = "application/json") 
public ResponseEntity<WalletDTO> createNewWallet(@Valid @RequestBody WalletMinimalInfoDTO walletInfo, BindingResult bindingResult) throws BindingException, NotFoundException, DuplicateException {
    
    
    log.info(String.format("Trying to save the wallet having address %s related to the user %s and to the coin %s", 
            walletInfo.getAddress(), 
            //walletDto.getUser().getEmail() 
            walletInfo.getUserId() != null ? walletInfo.getUserId() : "WALLET NOT YET ASSIGNED TO ANY USER", 
            walletInfo.getCoinCode()));
    
    if (bindingResult.hasErrors()) {
        String errorMessage = errMessage.getMessage(bindingResult.getFieldError(), 
                                                    LocaleContextHolder.getLocale());
        
        log.warning(errorMessage);

        throw new BindingException(errorMessage);
    }
    
    WalletDTO result = this.walletService.createNewWalletProxyFromWalletMinimalInfo(walletInfo);
    
    return new ResponseEntity<WalletDTO>(result, HttpStatus.OK);
    
}

So as you can see the previus controller method return the inserted DTO object to the client (so the client have the complete information of what was inserted)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2) The second adopted standard is that the controller method returns a response containing a message, something like this:

/**
 * Insert a new user belonging to the "sug-agent" user type
 * @throws BindingException 
 * @throws DuplicateException 
 */
@ApiOperation(
          value = "Insert a new user belonging to the \"sug-agent\" user type", 
          notes = "Insert a new user belonging to the \"sug-agent\" user type",
          produces = "application/json")
@PostMapping(value = "/subagent", produces = "application/json")
public ResponseEntity<?> insertSubAgentUser(@Valid @RequestBody User user, BindingResult bindingResult) throws BindingException, DuplicateException  {
    
    log.info(String.format("Saving the subagent user %s %s",user.getFirstName(), user.getSurname()));
    
    if (bindingResult.hasErrors()) {
        String errorMessage = errMessage.getMessage(bindingResult.getFieldError(), 
                                                    LocaleContextHolder.getLocale());
        
        log.warning(errorMessage);

        throw new BindingException(errorMessage);
    }
    
    HttpHeaders headers = new HttpHeaders();
    ObjectMapper mapper = new ObjectMapper();
    
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    ObjectNode responseNode = mapper.createObjectNode();
    
    User insertedUser = userService.insertSubAgentUser(user);
    
    responseNode.put("code", HttpStatus.OK.toString());
    responseNode.put("message", "Successfull insert of the user: " + insertedUser.getEmail());
    
    return new ResponseEntity<>(responseNode, headers, HttpStatus.CREATED);
    
}

As you can see the previous method insert an object into the DB but instead returning the entire obnject it is returning a JSON object containing only the operation status code and a message.

What do you think about? What is the standard and what could be the best choice?
My idea was to use the style 1 returning the entire object because it contains more information and because in my service method I am handling exception (returning proper error response in case of error).

>Solution :

At least for the client convenience , I would return the ID of the created object to let them know such that they can do further actions on the created object if necessary.

Because of this , if I will return the ID of the created object , why not simply do it further to return more data such that the client can know more about the created object. It may save them to make one less HTTP request in case they need to get the detail of the created object after it is created.

And in term of the implementation , after you know the ID of the created object in the backend , you just reuse the function that process GET /wallet/{walletId} to return the same response . So I don’t see it requires much extra efforts but can make the client feel more convenient to use the API.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading