Search code examples
javaresthttp

Is it ok to create entity in GET REST controller method with name getOrCreateIfNotExist?


So, I have some task, I have to create endpoint that should getOrCreateIfNotExist. But I`m not sure, is it ok practice to create some entity in the GET request. Or I should to do another call to the POST method to create new entity. Maybe like this:

    @GetMapping("")
    public List<SOMEOBJECT> getOrCreateIfNotExist(SOME DATA){
        return questionService.getOrCreateIfNotExist(SOME DATA);
    }

OR I should write like this:

    @GetMapping("")
    public List<SOMEOBJECT> getOrCreateIfNotExist(SOME DATA){
          if(questionService.getOrCreateIfNotExist(SOME DATA) == null){
             create(SOME DATA)
          }
    }

    @PostMapping("")
    public List<SOMEOBJECT> create(SOME DATA){
        return questionService.create(SOME DATA);
    }

I want to know what is best practice and is it good to do 2 things in one request?


Solution

  • The one with PostMapping is the more proper way to achieve the goal "get or create if not exist". Because if you want it to create, you are likely requiring the user to send the details you want to create (save).

    You should not use @GetMapping method if you want to create (save) object even when it does not exist.

    @PostMapping("")
        public List<SOMEOBJECT> create(SOME DATA){
            return questionService.create(SOME DATA);
        }
    

    And the function name create or in more detailed way : createOrGet should be fine.