Muhammad2015-05-09 10:41:22
Muhammad, 2015-05-09 10:41:22

API architecture on Laravel?

Hello. I'm making a small API for AJAX requests. The API route itself looks like this:

Route::group(array('prefix' => 'api'), function()
  Route::any('/v{version}/{group}.{method}.{type?}', '[email protected]');

I created a new namespace and wrote in the controller:
public function callMethod($version, $controller, $method, $responseType =  'json')
  $api = new Api\Api();

  return $api->callMethod($controller, $method, $responseType);

Everything is OK until I want to create a new version of the API, keeping the old one. Thought to do it like this:
public function callMethod($version, $controller, $method, $responseType =  'json')
  $directory = 'v' . $version;
  $className = "Api\\$directory\\Api()";

  $api = new $className();

  return $api->callMethod($controller, $method, $responseType);;

and create a separate folder for each version. But in this case, you will have to change namespaces in all classes, which, in my opinion, is not entirely correct. Maybe there is another option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Sergey, 2015-05-09

Maybe there is another option?

Yes, there is, stop suffering from garbage with universal routing settings (you still have to tweak something later) and make a normal REST / JSON RPC API, with its own rules for each API method.
laravel.com/docs/5.0/controllers#restful-resource-... - it generally makes sense to use such things.
According to API versions - you can resolve it through middleware.
As for {type}, it's not cool at all, if you want to get json instead of xml, then just write application/json in Accept, and don't cast spells in the URI. Although it is more convenient for you of course.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question