MVC and RESTful API – How to Integrate

apiapi-designdesign-patternsmvcrest

MVC is pretty straightforward. There is a Model, a Controller and a View. When we create a website, it all come together as 'client sends REST keyword request to server -> the server matches the requested URL to the controller action -> which then calls the model(s) for data gathering/processing, gets the result -> and returns the result back to the client as a HTML page (view)'.

What if we are talking about a pure RESTful API web service? Then the flow with be something like 'client sends REST keyword request to server -> the server matches the requested URL to the controller action -> which then calls the model(s) for data gathering/processing, gets the result -> and returns the result back to the client in JSON'. Same as before, but there is no 'view'…or rather, the generated JSON can be thought of as a 'view'. In a sense, we are only utilizing the MC part of MVC. Is that how it is should be done? Or are there any other, better-suited patterns for a API-only service instead of MVC?

Best Answer

MVC is a paradigm from the Smalltalk world concerned with how object orientated systems could have UIs.

Early web frameworks took the general idea (separate out business logic, controlling logic and view logic) and applied the principle to how they structured the web application. Before this it wasn't uncommon to have a mess of HTML generation code inside domain objects, or business logic inside HTML templates (think very early PHP)

The thing is that the original MVC from the Smalltalk world isn't really what MVC is in most web frameworks. A HTML output isn't really a "view" in the sense that Smalltalk understood a UI screen to be.

So that is the first reason not to get too hung up on whether you are following MVC properly. Hardly anything is. Take it less as a strict division and more a guideline of Hey wouldn't it be nice if our HTML templates weren't full of business logic.

Secondly MVC is just a way of structuring server side code. It really has nothing to do with REST/HTTP. REST is concerned with how clients and servers communicate. It doesn't care if the representation the server sends to the client is in a HTML template that took a lot to construct with a templating engine, or a JSON object that was one call in the controller.

If you don't think your server needs a "view" layer, that is fine. You will still gain benefit separating out your business logic (ie model) from the controllers that are handling a specific HTTP request, even if all the controller does it call a JSON parsing call on some object and return that data.