Logo

dev-resources.site

for different kinds of informations.

Quando usar ResponseEntity?

Published at
1/9/2025
Categories
webdev
java
springboot
spring
Author
oigorrudel
Categories
4 categories in total
webdev
open
java
open
springboot
open
spring
open
Author
10 person written this
oigorrudel
open
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
springboot Article's
30 articles in total
Favicon
Launched a Web version of my Project using Java Spring Framework, Spring Boot Web
Favicon
Understanding Spring Security and OAuth 2.0
Favicon
Spring Oauth2 - App-Token based Hybrid Token Verification Methods
Favicon
Static variables in Java
Favicon
What is Spring AI ? Example of a chat API with multiple LLMs
Favicon
Quando usar ResponseEntity?
Favicon
App-Token based easy OAuth2 implementation built to grow with Spring Boot
Favicon
[Boost]
Favicon
Spring Boot 3 application on AWS Lambda - Part 14 Measuring cold and warm starts with GraalVM Native Image and memory settings
Favicon
SpringBoot Web Service - Part 5 - Github Action
Favicon
Apache wicket with spring boot example application: notice board
Favicon
OTP Authentication: The Passwordless Superhero of Your App! 🦸‍♂️✨
Favicon
SpringBoot Web Service - Part 1 - Create Repository
Favicon
SpringBoot Web Service - Part 2 - Preparing Using Spring Initializr
Favicon
Zero Config Spring Batch: Just Write Business Logic
Favicon
Generate a REST API Using Java and Spring Boot for your Postgres database
Favicon
How to optimize SpringBoot startup
Favicon
Spring Boot: About @SpringBootApplication
Favicon
Introduction to Spring Boot: A Complete Guide
Favicon
Wednesday Links - Edition 2025-01-01🎉
Favicon
SpringBoot Web Service - Part 4 - Initial Configuration
Favicon
How to implement detekt in Spring Boot + Kotlin + Gradle project
Favicon
Building Resilient APIs: Mistakes I Made and How I Overcame Them
Favicon
Web Scraping Summarization with Vite React TypeScript and Spring Boot
Favicon
Handling NullPointerException with Optional
Favicon
Overview of Lock API in java
Favicon
Optimizing Serverless Lambda with GraalVM Native Image
Favicon
With Spring can I make an optional path variable?
Favicon
Building a Vue CRUD App with a Spring Boot API
Favicon
Hexagonal Architecture — A Favorite Lyrics Spring Boot — Java Example

Featured ones: