Reputation: 3258
I'm building a web application built on top of Symfony which is going to have normal web pages to input data and also some REST APIs. For example, I could have a page to create a new item and I want a REST endpoint too. I'm now struggling thinking at which is the best way to handle two endpoints for the same thing: should I have different code to handle the two formats separately or should I use something like FOSRestBundle which handles in one method the same API for HTTP and REST? Obviously the latter has the advantage that I shouldn't replicate the code twice, but I have some doubts if I want to have specific code for the HTML version of the endpoint. In the end, how big sites design their application to handle standard pages and REST APIs?
Upvotes: 0
Views: 235
Reputation: 3109
I would generally advocate for having separate endpoints for my REST service. My reasoning follows:
Using an MVC architecture, you're going to have a view sitting server side. The controller (endpoint) for that view may have logic specific to the HTML rendering that's going to occur server side. The view itself may also have some logic in your server-side view.
When it comes to using RESTful services, you might have the same (or some of the same) logic server side, but you also might have entirely different logic, or place some logic in your partial template that you use client-side after fetching data from the server.
Generally, I expose a server-side services layer to abstract out my DAL (data access layer), so if there is a need for IDENTICAL code from server-side controller & RESTful service, you can just abstract that logic out to a central service layer, call it from both cases, and avoid code duplication, while still having the flexibility to build out separate functionality for HTTP vs REST calls. I don't like seeing something like this:
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
die($content);
}
Upvotes: 1