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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read 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

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay