Home > Blockchain >  How to use GET and POST method according to their responsibilities in Spring REST
How to use GET and POST method according to their responsibilities in Spring REST

Time:11-05

I want to return an object which is created on the server side but the method doesn't need any request parameter or request body to create the object. In this scenario, I couldn't decide which method should I use. Should I use GET or POST?

@GetMapping("/")
public ResponseEntity<InitializeResponse> getNewlyCreated() {
    X x = new X();
    x = service.initialize(x.getId());
    return ResponseEntity.ok().body(new InitializeResponse(x));
}

But this doesn't seem right to me because method return newly created object, which leads me to change the responsibility to POST but in order to make it POST method, as far as I know I need a request body or request parameter to create the object according to them.

Which method should I use?

CodePudding user response:

You don't have to use a body or request parameters with a POST request. You can use both, POST allows them, but they are not mandatory. However, POST is definitely the right choice for your usecase, since a GET request should not change the state of your application, which you are doing (i am assuming that you are storing the object, which you create in this method, somewhere e.g. in a database). If you don't store anything but just return that object (e.g. like with a conversion tool, where you just convert and return some data), a GET request type would be sufficient as well.

  • Related