Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should one serve swagger from laravel?

I'm attempting to use swagger with laravel to automatically document our RESTful API. The goal is to keep the swagger comments in the laravel controllers and then have swagger parse the comments and generate the associated .json/.php files. Ideally, I'm looking to have the swagger files be served by the laravel project so that everything is kept under the same hood and in sync.

In order to accomplish this, I have created a docs directory in the root directory of my laravel project (same directory that public resides in). I've then added the following route to routes.php:

Route::get('docs/{page?}', function($page='index.php') {
    header('Access-Control-Allow-Origin: *');
    $parts = pathinfo($page);
    $path = $_SERVER["DOCUMENT_ROOT"] . "/../docs/$page";
    if ($parts['extension'] === 'php') {
        require($path);
    } else {
        return file_get_contents($path);
    }
});

Using this method I am then able to point my swagger-ui website to http://mydomain/docs and the rest is magic.

For all you laravel gurus out there, is this the best way to serve these swagger files? I tried putting the docs directory in public but this leads to a redirect loop.

Another way to accomplish this is to create a virtual host in my web server config that points directly to these swagger files, but at this point I'd prefer not to have to make this extra configuration.

like image 371
redgeoff Avatar asked May 07 '14 00:05

redgeoff


1 Answers

I wrote swaggervel, a package for Laravel, which auto-generates your swagger json using swagger-php, serves it with redgeoff's code, and then displays it using swagger-ui.

Just add the follow line to the require in your composer.json:

"jlapp/swaggervel": "dev-master"

Alternatively you can get it on Git: https://github.com/slampenny/Swaggervel.git

like image 58
Jordan Lapp Avatar answered Nov 02 '22 14:11

Jordan Lapp