DEV Community

Discussion on: How I structure my REST APIs

Collapse
 
larswaechter profile image
Lars Wächter • Edited

1)
If we have the services (logic) separated from the controllers, we can query the required data from anywhere else in our codebase. Otherwise you have to write the same code every time again just to get the same data. (or you send a request to the API itself -> bad)

2)
A route does not directly call a service, because before calling the service the controller takes care of the incoming HTTP request, validation and the outgoing response. In a controller we might send different HTTP status codes or prepare the data before sending it back to the client. In a service we just load the data and handle the business logic. It does not care about where it gets called from.

Let's say you call a service, that expects parameters, directly from a route. Now the router sends the incoming HTTP request as argument to your service. But what if you want to call the service from within your codebase and not from an incoming HTTP request? You can't really pass a HTTP request as argument.

Collapse
 
utkal97 profile image
Utkal

Thank you. Everything is clarified now.