DEV Community

Rakesh Sagar
Rakesh Sagar

Posted on

2

[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}.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️