DEV Community

Igor Rudel
Igor Rudel

Posted on

2

Quando usar ResponseEntity?

Vejamos a controller com o endpoint abaixo:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    public ResponseEntity<String> get() {
        return ResponseEntity.ok("Hello World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Quando se utiliza a anotação @RestController do Spring, por default os responses são colocados nos body's das respostas, é desnecessário o uso de ResponseEntity tipificando o retorno do método, apenas o tipo da resposta diretamente, como no exemplo abaixo:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    public String get() {
        return "Hello World!";
    }
}
Enter fullscreen mode Exit fullscreen mode

Também, por default, no caso de sucesso, o status code utilizado nos enpoints é 200 (OK), ou seja, só se faz necessário alterá-lo quando é desejado utilizar outro status, e não precisa ser utilizado ResponseEntity, basta utilizar a anotação @ResponseStatus acima do método:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    @ResponseStatus(HttpStatus.ACCEPTED)
    public String get() {
        return "Hello World!";
    }
}
Enter fullscreen mode Exit fullscreen mode

Então porque existe a ResponseEntity?

Para casos em que você precisa adicionar mais informações na resposta que não apenas o body e o status, como por exemplo adicionar um header ao response:

@RestController
@RequestMapping("v1/hello")
public class ExampleController {

    @GetMapping
    public ResponseEntity<String> get() {
        return ResponseEntity.ok()
            .header("X-Test", "Blabla")
            .body("Hello World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

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

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay