Search code examples
spring-boothttp-status-codes

Return response messages in spring boot


I am working with spring boot with a h2 database. I would like to return a 201 message when the register is inserted succesfully and a 400 when is duplicated. I am using ResponseEntity to achieve this, fot example , the next is my create method from the Service:

    @Override
    public ResponseEntity<Object> createEvent(EventDTO eventDTO) {
        if (eventRepository.findOne(eventDTO.getId()) != null) {
            //THis is a test, I am looking for the correct message
            return new ResponseEntity(HttpStatus.IM_USED);
        }
        Actor actor = actorService.createActor(eventDTO.getActor());
        Repo repo = repoService.createRepo(eventDTO.getRepo());
        Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
        eventRepository.save(event);
        return new ResponseEntity(HttpStatus.CREATED);
    }

This is my controller:

    @PostMapping(value = "/events")
    public ResponseEntity addEvent(@RequestBody EventDTO body) {
        return eventService.createEvent(body);
    }

But I'm not getting any message in the browser, I am doing different tests with postman and when I consult for all the events, the result is correct, but each time that I make a post I dont get any message in the browser, I am not pretty sure what is the cause of this issue. Any ideas?


Solution

  • The ideal way to send Response to the client is to create DTO/DAO with ResponseEntity in Controller

    Controller.java

    @PostMapping("/test")
            public ResponseEntity<Object> testApi(@RequestBody User user)
            {
                System.out.println("User: "+user.toString());
                return assetService.testApi(user);
            }
    

    Service.java

    public ResponseEntity testApi(User user) {  
            if(user.getId()==1)
                return new ResponseEntity("Created",HttpStatus.CREATED);
            else
                return new ResponseEntity("Used",HttpStatus.IM_USED);   
               // for BAD_REQUEST(400) return new ResponseEntity("Bad Request",HttpStatus.BAD_REQUEST);
        }
    

    Tested using Postman

    Status 201 Created Created

    Status 226 IM Used Status IMUSED