Question

I'm working in a RESTFul API with laravel, and I want to use content negotiation in my project, but I don't know how to accomplish that. I have my controllers separted by api version, and I want to distinguish between api versions and use the correct controllerdepending on the version.

My API router is:

Route::group(array('prefix' => 'api'), function() {
    Route::resource('users', 'API\V1\UsersController');
});

Should I create a api.type filter to use in my route group or Should I do that in the route group clousure or maybe, in each controller?

Was it helpful?

Solution

Don't be afraid to branch out your application logic into library classes. You don't have to fit everything inside of Laravel's given folder structure.

In fact, adding in your own namespaced group of classes can have a big benefit. You can see some setup on creating your own application library here.

Once you have that set up, you can create a class whose responsibility is to decide what content type to return. This might be based on an Accept header, URL parameter or whatever you define (That's up to you, the API creator).

Perhaps this class will take the Accept header and normalize it to something like "json", "xml" and "html".

The Request class has some methods to help you if you do it via the Accept header.

So, in pseudo code (syntax errors to follow!), your controller might do something like this:

/* GET /api/users */
public function index()
{
    // Might return "json" or "xml" or "html"
    $contentType = \My\ContentType\Class->getContentType();

    $users = User::all();

    // Not shown here is logic to set `content-type` header in the returned response (json vs xml vs html)
    // Perhaps a method to go into your implementation of \My\ContentType\Class
    return View::make('users.'.$contentType)->with(array( 'users' => $users ));


}

That's just an idea of what you might do. The key point is to get yourself working in a library that you can put business logic into to get you started with an idea of how to accomplish adding in business logic for your application.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top