Rest – Strategy for Website Talking to API on Same Server

apidesignrest

I have a RESTful API that allows retrieval of data through requests such as GET http://example.com/users/id/1 (Coded following this tutorial).

The code igniter controller looks like this:

class Example_api extends REST_Controller {

function user_get()
{
    $data = array('returned: '. $this->get('id'));
    $this->response($data);
}

This API was written specifically for the reason that I should be able to access the same code logic from the web frontend as well as mobile apps etc. Now, the mobile app is easy to write but I want to find the strategy for using the API from the web site. The website is essentially sitting on the same server that offers this API and it does not seem right to me to make an HTTP request to the API from code and go through the network again.

So, the question is, how do I use the API from the php code in the same site without going through the network.

Best Answer

It sounds like both the API and the website share a common language (PHP). In such a scenario I often find that the functionality used by the API can often be abstracted out into a less API specific object that other solutions (like the website) can also utilize.

This object would serve as a shared interface for the website and the API. Very little functionality then needs to live in the API code as it is simply operating as a translation layer between HTTP requests and the object.

It also saves the website from having to make network calls to an API and allows it to interact with the object more naturally.

If your API's functionality is relatively simple this runs the risk of being an over-architected approach so you'll need to consider if this is necessary and maintainable in your specific situation.

Related Topic