Advice on using separate controllers for the REST API or not?

we are planning a REST api for our application and are trying to make a decision on whether we should implement separate controllers for REST functionality or not.

We could use withFormat {} in our current controllers, but sharing the REST functionality in different controllers is a little cleaner ..

Thus, we can build our API separately from the current controllers and we could even take the REST controllers into another application, etc.

Any thoughts on this? Any real experience in best practice will be?

+4
source share
3 answers

We recently encountered the same solution and decided to use separate controllers for the REST API.

The benefits of individual controllers include clean / clear controllers and the ability to support different versions of the REST API later.

We would also like to keep the ability to host the REST API on separate server instances. These servers will use the exact same .war, but with different configuration settings for the function to switch .

The disadvantage of individual controllers may be DRY controller code. Although this should be limited, since IMHO you should keep the controllers as thin as possible and extract common logic for Grails services or helper classes.

+3
source

I will work with the grail soon, but so far I have little experience. But in the web applications that I worked on, we always left web services separate from the controller code. We also shared REST with SOAP. Common methods for them will be at the service level. He really felt cleaner. We did not have to insert a lot of if into methods

0
source

I would use one controller for this resource that interacts with the context-based service layer (type or type of media received or requested - SOAP, JSON, XML, etc.) So you have a really uniform resource identifier that can receive and return various types of media, and the controller does not need to know anything except what method the user wants to execute on which resource and in what type of media.

For example, perhaps the service level returns objects that have methods such as "toXml", "toSoap", or "toJson". Then you can simply ask the service level to do anything and use the switch statement on the requested media type to either return the requested information or display the 406 Not Acceptable status code by default. For unsafe or idempotent transactions, an object may have constructor or factory methods for this type of media, and then you simply request that the service level do something with this object.

0
source

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


All Articles