How should one serve swagger from laravel?
Asked Answered
A

2

9

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.

Alphonso answered 7/5, 2014 at 0:20 Comment(0)
B
8

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

Blandishment answered 8/7, 2014 at 22:53 Comment(1)
the problem I am seeing is....and then what....swagger documentation is limited and I can't find any tutorials on what to do in 5.2 AFTER you have installed this packageEpistrophe
P
0

I'm working on this now, I've solved the redirect loop but not as elegantly as I'd like.

Just add a .htaccess file in your public/docs/ dir with the following:

<IfModule mod_rewrite.c>
    RewriteEngine On
</IfModule>

you'll be able to access the file without typing out index.php. I'll update if I come up with a more elegant way of generating documentation.

Pentadactyl answered 14/5, 2014 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.