DEV Community

Rakesh Sagar
Rakesh Sagar

Posted on

[TIL] A better response to post request (Spring Boot)

When writing an api that saves the data it would be nice if there was a way to see the the data stored. So usually the id is returned in the response of the api.
Spring Boot provides a better way to handle this, By providing the created method in response entity which accepts a url as an argument and returns 201 as he response status.

ResponseEntity.created(
  URI.create("http://domainname/getEndpoint/"+entity.getId())
).build();
Enter fullscreen mode Exit fullscreen mode

This would apply a response header called Location with the above mentioned url.

Image description

However, we want to make the domain name dynamic as the api can be deployed in multiple environments.
A quick google search led me to this Stack Overflow Answer

I'd like to create URLs based on the URL used by the client for the active request. Is there anything smarter than taking the current HttpServletRequest object and it's getParameter...() methods to rebuilt the complete URL including (and only) it's GET parameters.

Clarification: If possible I want to resign from

Here is the code snippet for that

URI uri = ServletUriComponentsBuilder
             .fromCurrentContextPath()
         .path("/get/{id}")
             .build(String.valueOf(entity.getId()));

return ResponseEntity.created(uri).build();
Enter fullscreen mode Exit fullscreen mode

and the final response

Image description

Conclusion (da ta daaa) So after almost a year I posted here again. Any form of constructive critisism is always welcome with open arms. So.. see you around I guess ${insert akward goodbye}.

Top comments (0)