Where should I wrap my REST Response, controller or service?

I am building a web application in Spring MVC that has a controller level and a service level. My answers are wrapped in a user wrapper that includes the payload and metadata regarding the result of the call (regardless of whether the payload was successful, includes only partial data, etc.) so that I can return HTTP 200 and allow metadata to describe the result call to the client.

Initially, I wrapped the response in the called service, and the controller simply passed the response. However, this template does not work when I need to call my service from other services, because I need to deploy the data first, do some work on it, and then wrap it again and send it back to the controller. Because of this, I started creating a response in controllers.

The problem is that I want my controllers to be as small as possible, to be clear and readable as a mapping of URLs for services.

Are the controllers the right place to create a REST response wrapper or should I leave it in the services?

+4
source share
3 answers

, HTTP . - Spring, . , , .

, . , , , . , , , , . .

, HTTP- .

  • . , , , HTTP. Spring MVC HTTP @ExceptionHandler. .

  • HTTP. , , HTTP, JSON. POJO, , HTTP.

  • . API . , , JSON JSON HTTP. , , , , URL- . JSON .

  • Spring . Spring Framework. RestTemplate, Spring MVC. , -. ( , , ).

, , . , 200 (OK) 201 (). , ( ). , . , . .

+3

REST ?

, : . - - - -. , . Meta-Services . , . .

( Spring @Controller) -. , : , . .

, , , : .

+1

Think of the following case: let's say some new external consumer of your data needs the same data that you return to your REST controller (provided that you return JSON), but can only process XML. Which would you prefer? Write a new service level that returns XML if your current returns JSON, or just write a new controller method that returns XML from the general service level?

+1
source

Source: https://habr.com/ru/post/1532923/


All Articles