Sunday, April 24, 2016

Laravel Swagger Integration for API and Code Documentation

I know, I know, all developers hate documentation. Even I also don't like it but it's an industry practice and we have to follow this. In this blog I am going to explain how you can integrate swagger most popular framework for API with Laravel for creating API docs. Swagger is an incredible way to easily document and test your APIs. So here is the step by step guides.

1) Go to your laravel project on Terminal and include Swagger PHP package with composer.

composer require zircote/swagger-php

This will install swagger php package to laravel and will update your vendor folder. Now we have to create documentation.

2) There is standard syntax for creating docs with swagger. For each API functions and classes you have to add swagger config and config have all the standard keys to define what kind of information you will include in docs. You can check this on following URL.

Hover mouse on left side object and it will give you information on right side.

This you have to add in add in your controllers and models in your laravel project. So lets define some basic info. For example see following swagger config we have added. This we have added a comments to top of the controller function.

     *     basePath="",
     *     schemes={"http"},
     *     @SWG\Info(
     *         version="1.0",
     *         title="Sample API",
     *         @SWG\Contact(name="Hiren Dave", email=""),
     *     ),
     *   @SWG\Get(
     *     path="/",
     *     description="Returns basic information",
     *     produces={"application/json"},
     *     @SWG\Response(
     *         response=200,
     *         description="Application Overview"
     *     )
     *   )
     * )

And following is my API function.

        public function index()
              return Response::json(array('success'=>false,'message'=>'This is Basic Info of API'));

It have basic info like API info and API path and output information.

3) Build Swagger Docs.

Go to your laravel project in terminal and run following command.

./vendor/bin/swagger ./app/Http

It will generate swagger.json file in your root folder with all the swagger config you have added in your controller. 

4) Add swagger UI to project to show this docs.

Go to following link to download swagger UI.

Download it and copy all the files from dist folder to your public/docs folder. Now open public/docs/index.html page and update path of your swagger.json file in following code.

if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "";

Change URL to url your own swagger.json URL, for example in my case it was http://localhost/laravel-swagger/swagger.json

5) Read the Docs. Now go to public docs folder. In my case URL was


When you run, you will see following output page.

That's it and you have your API docs minimum efforts. Hope this helps you.

No comments:

Post a Comment