📒📚Generate beautiful interactive documentation and Open-API 3.0 spec file from your existing Laravel app.

Overview



Latest Stable Version Total Downloads License

              Follow me anywhere @ovac4u                         | GitHub
              _________                          _________       | Twitter
             |   ___   |.-----.--.--.---.-.----.|  |  |.--.--.   | Facboook
             |  |  _   ||  _  |  |  |  _  |  __||__    |  |  |   | Instagram
             |  |______||_____|\___/|___._|____|   |__||_____|   | Github + @ovac
             |_________|                        www.ovac4u.com   | Facebook + @ovacposts


Laravel IDoc - The API Documentation Generator

Automatically generate an interactive API documentation from your existing Laravel routes. Take a look at the example documentation. Inspired by Laravel Api Documentation Generator



Introduction.

Laravel IDoc generator (interactive documentation generator) is a seamless and complete plugin for generating API documentation from your Laravel's codebase. It is inspired by the laravel-apidoc-generator, ReDoc and the Open API initiative from Swagger. IDoc has been built with extendability so that it can easily adapt with your use case.

Demo

Features

  • Extremely easy deployment
  • Server Side Rendering ready
  • The widest OpenAPI v2.0 features support
    {.inline}
  • OpenAPI 3.0 support
  • Neat interactive documentation for nested objects
    {.inline}
  • Automatic code sample support
    {.inline}
  • Responsive three-panel design with menu/scrolling synchronization
  • Integrate API Introduction into side menu.
  • High-level grouping in side-menu.
  • Branding/customizations.

Installation

Note: PHP 7 and Laravel 5.5 or higher are the minimum dependencies.

$ composer require ovac/idoc

Laravel

Publish the config file by running:

php artisan vendor:publish --tag=idoc-config

This will create an idoc.php file in your config folder.

Lumen

  • Register the service provider in your bootstrap/app.php:
$app->bind('path.public', function ($app) { return $app->basePath('../your-public-path'); });
$app->register(\OVAC\IDoc\IDocLumenServiceProvider::class);
  • Copy the config file from vendor/ovac/idoc/config/idoc.php to your project as config/idoc.php. Then add to your bootstrap/app.php:
$app->configure('idoc');

Usage

$ php artisan idoc:generate

Configuration

Before you can generate your documentation, you'll need to configure a few things in your config/idoc.php.

  • path This will be used to register the necessary routes for the package.
'path' => 'idoc',
  • logo You can specify your custom logo to be used on the generated documentation. A relative or absolute url to the logo image.
'logo' => 'https://res.cloudinary.com/ovac/image/upload/h_300,w_380,c_fill,r_30,bo_20px_solid_white/aboust_ey5v1v.jpg',
  • title Here, you can specify the title to place on the documentation page.
'title' => 'iDoc API Reference',
  • description This will place a description on top of the documentation.
'description' => 'iDoc Api secification and documentation.',
  • version Documentation version number.

  • terms_of_service This is the url to the terms and conditions for use your API.

  • contact Here you can configure contact information for support.

'contact' => [
        'name' => 'API Support',
        'email' => '[email protected]',
        'url' => 'http://www.ovac4u.com'
],
  • license A short and simple permissive license with conditions only requiring preservation of copyright and license notices
'license' => [
        'name' => 'MIT',
        'url' => 'https://github.com/ovac/idoc/blob/master/LICENSE.md'
],
  • output This package can automatically generate an Open-API 3.0 specification file for your routes, along with the documentation. This is the file path where the generated documentation will be written to. Default: public/docs

  • hide_download_button This section is where you can configure if you want a download button visible on the documentation.

  • router The router to use when processing the route (can be Laravel or Dingo. Defaults to Laravel)

  • servers The servers array can be used to add multiple endpoints on the documentation so that the user can switch between endpoints. For example, This could be a test server and the live server.

'servers' => [
   [
       'url' => 'https://www.ovac4u.com',
       'description' => 'App live server.',
   ],
   [
       'url' => 'https://test.ovac4u.com',
       'description' => 'App test server.',
   ],
],
  • tag_groups This array is used to separate groups that you have defined in little sections in the side menu. If you want to use it, make sure you add all groups because the unadded group will not be displayed.

  • language-tabs This is where you can set languages used to write request samples. Each item in array is used to generate a request template for a given language. New languages can be added and the existing ones modified after. You can add or edit new languages tabs by publishing the view files and editing them or adding custom view files to:

'resources/views/vendor/idoc/languages/LANGUAGE.blade.php',
  • security This is where you specify authentication and authorization schemes, by default the HTTP authentication scheme using Bearer is setting but you can modify it, add others or even define it as null according to the requirements of your project. For more information, please visit Swagger Authentication.
'security' => [
       'BearerAuth' => [
           'type' => 'http',
           'scheme' => 'bearer',
           'bearerFormat' => 'JWT',
       ],
   ],
  • routes This is where you specify what rules documentation should be generated for. You specify routes to be parsed by defining conditions that the routes should meet and rules that should be applied when generating documentation. These conditions and rules are specified in groups, allowing you to apply different rules to different routes.

For instance, suppose your configuration looks like this:

return [
     //...,
  
     /*
     * The routes for which documentation should be generated.
     * Each group contains rules defining which routes should be included ('match', 'include' and 'exclude' sections)
     * and rules which should be applied to them ('apply' section).
     */
    'routes' => [
        [
            /*
             * Specify conditions to determine what routes will be parsed in this group.
             * A route must fulfill ALL conditions to pass.
             */
            'match' => [

                /*
                 * Match only routes whose domains match this pattern (use * as a wildcard to match any characters).
                 */
                'domains' => [
                    '*',
                    // 'domain1.*',
                ],

                /*
                 * Match only routes whose paths match this pattern (use * as a wildcard to match any characters).
                 */
                'prefixes' => [
                    'api/*',
                ],

                /*
                 * Match only routes registered under this version. This option is ignored for Laravel router.
                 * Note that wildcards are not supported.
                 */
                'versions' => [
                    'v1',
                ],
            ],

            //...
        ],
    ],

This means documentation will be generated for routes in all domains ('*' is a wildcard meaning 'any character') which match any of the patterns 'api/*' or 'v2-api/*', excluding the 'users.create' route and any routes whose names begin with admin., and including the 'users.index' route and any routes whose names begin with healthcheck.. (The versions key is ignored unless you are using Dingo router). Also, in the generated documentation, these routes will have the header 'Authorization: Bearer: {token}' added to the example requests.

You can also separate routes into groups to apply different rules to them:

<?php
return [
     //...,
  
     'routes' => [
          [
              'match' => [
                  'domains' => ['v1.*'],
                  'prefixes' => ['*'],
              ],
              'include' => [],
              'exclude' => [],
              'apply' => [
                  'headers' => [
                      'Token' => '{token}',
                      'Version' => 'v1',
                  ],
              ],
          ],
          [
              'match' => [
                  'domains' => ['v2.*'],
                  'prefixes' => ['*'],
              ],
              'include' => [],
              'exclude' => [],
              'apply' => [
                  'headers' => [
                      'Authorization' => 'Bearer: {token}',
                      'Api-Version' => 'v2',
                  ],
              ],
          ],
];

With the configuration above, routes on the v1.* domain will have the Token and Version headers applied, while routes on the v2.* domain will have the Authorization and Api-Version headers applied.

Note: the include and exclude items are arrays of route names. THe * wildcard is supported. Note: If you're using DIngo router, the versions parameter is required in each route group. This parameter does not support wildcards. Each version must be listed explicitly,

To generate your API documentation, use the idoc:generate artisan command.

$ php artisan idoc:generate

It will generate documentation using your specified configuration.

Documenting your API

This package uses these resources to generate the API documentation:

Grouping endpoints

This package uses the HTTP controller doc blocks to create a table of contents and show descriptions for your API methods.

Using @group in a controller doc block creates a Group within the API documentation. All routes handled by that controller will be grouped under this group in the sidebar. The short description after the @group should be unique to allow anchor tags to navigate to this section. A longer description can be included below. Custom formatting and <aside> tags are also supported. (see the Documentarian docs)

Note: using @group is optional. Ungrouped routes will be placed in a "general" group.

Above each method within the controller you wish to include in your API documentation you should have a doc block. This should include a unique short description as the first entry. An optional second entry can be added with further information. Both descriptions will appear in the API documentation in a different format as shown below. You can also specify an @group on a single method to override the group defined at the controller level.

/**
 * @group User management
 *
 * APIs for managing users
 */
class UserController extends Controller
{

	/**
	 * Create a user
	 *
	 * [Insert optional longer description of the API endpoint here.]
	 *
	 */
	 public function createUser()
	 {

	 }
	 
	/**
	 * @group Account management
	 *
	 */
	 public function changePassword()
	 {

	 }
}

Specifying request parameters

To specify a list of valid parameters your API route accepts, use the @bodyParam, @queryParam and @pathParam annotations.

  • The @bodyParam annotation takes the name of the parameter, its type, an optional "required" label, and then its description.
  • The @queryParam annotation takes the name of the parameter, an optional "required" label, and then its description
  • The @pathParam annotation takes the name of the parameter, an optional "required" label, and then its description
/**
 * @group Items
 */
class ItemController extends Controller
{

    /**
     * List items
     *
     * Get a list of items.
     *
     * @authenticated
     * @responseFile responses/items.index.json
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //...
    }

    /**
     * Store item
     *
     * Add a new item to the items collection.
     *
     * @bodyParam name string required
     * The name of the item. Example: Samsung Galaxy s10
     *
     * @bodyParam price number required
     * The price of the item. Example: 100.00
     *
     * @authenticated
     * @response {
     *      "status": 200,
     *      "success": true,
     *      "data": {
     *          "id": 10,
     *          "price": 100.00,
     *          "name": "Samsung Galaxy s10"
     *      }
     * }
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //...
    }


    /**
     * Get item
     *
     * Get item by it's unique ID.
     *
     * @pathParam item integer required
     * The ID of the item to retrieve. Example: 10
     *
     * @response {
     *      "status": 200,
     *      "success": true,
     *      "data": {
     *          "id": 10,
     *          "price": 100.00,
     *          "name": "Samsung Galaxy s10"
     *      }
     * }
     * @authenticated
     *
     * @param  \App\Item  $item
     * @return \Illuminate\Http\Response
     */
    public function show(Item $item)
    {
        //...
    }

They will be included in the generated documentation text and example requests.

Result: Result

Note: a random value will be used as the value of each parameter in the example requests. If you'd like to specify an example value, you can do so by adding Example: your-example to the end of your description. For instance:

    /**
     * @pathParam location_id required The id of the location.
     * @queryParam user_id required The id of the user. Example: me
     * @queryParam page required The page number. Example: 4
     * @bodyParam user_id int required The id of the user. Example: 9
     * @bodyParam room_id string The id of the room.
     * @bodyParam forever boolean Whether to ban the user forever. Example: false
     */

Note: You can also add the @bodyParam annotations to a \Illuminate\Foundation\Http\FormRequest subclass:

/**
 * @bodyParam title string required The title of the post.
 * @bodyParam body string required The title of the post.
 * @bodyParam type string The type of post to create. Defaults to 'textophonious'.
 * @bodyParam author_id int the ID of the author
 * @bodyParam thumbnail image This is required if the post type is 'imagelicious'.
 */
class MyRequest extends \Illuminate\Foundation\Http\FormRequest
{

}

public function createPost(MyRequest $request)
{
    // ...
}

Indicating auth status

You can use the @authenticated annotation on a method to indicate if the endpoint is authenticated. A field for authentication token will be made available and marked as required on the interractive documentation.

Providing an example response

You can provide an example response for a route. This will be displayed in the examples section. There are several ways of doing this.

@response

You can provide an example response for a route by using the @response annotation with valid JSON:

/**
 * @response {
 *  "id": 4,
 *  "name": "Jessica Jones",
 *  "roles": ["admin"]
 * }
 */
public function show($id)
{
    return User::find($id);
}

Moreover, you can define multiple @response tags as well as the HTTP status code related to a particular response (if no status code set, 200 will be returned):

/**
 * @response {
 *  "id": 4,
 *  "name": "Jessica Jones",
 *  "roles": ["admin"]
 * }
 * @response 404 {
 *  "message": "No query results for model [\App\User]"
 * }
 */
public function show($id)
{
    return User::findOrFail($id);
}

@transformer, @transformerCollection, and @transformerModel

You can define the transformer that is used for the result of the route using the @transformer tag (or @transformerCollection if the route returns a list). The package will attempt to generate an instance of the model to be transformed using the following steps, stopping at the first successful one:

  1. Check if there is a @transformerModel tag to define the model being transformed. If there is none, use the class of the first parameter to the transformer's transform() method.
  2. Get an instance of the model from the Eloquent model factory
  3. If the parameter is an Eloquent model, load the first from the database.
  4. Create an instance using new.

Finally, it will pass in the model to the transformer and display the result of that as the example response.

For example:

/**
 * @transformercollection \App\Transformers\UserTransformer
 * @transformerModel \App\User
 */
public function listUsers()
{
    //...
}

/**
 * @transformer \App\Transformers\UserTransformer
 */
public function showUser(User $user)
{
    //...
}

/**
 * @transformer \App\Transformers\UserTransformer
 * @transformerModel \App\User
 */
public function showUser(int $id)
{
    // ...
}

For the first route above, this package will generate a set of two users then pass it through the transformer. For the last two, it will generate a single user and then pass it through the transformer.

Note: for transformer support, you need to install the league/fractal package

composer require league/fractal

@responseFile

For large response bodies, you may want to use a dump of an actual response. You can put this response in a file (as a JSON string) within your Laravel storage directory and link to it. For instance, we can put this response in a file named users.get.json in storage/responses:

{"id":5,"name":"Jessica Jones","gender":"female"}

Then in your controller, link to it by:

/**
 * @responseFile responses/users.get.json
 */
public function getUser(int $id)
{
  // ...
}

The package will parse this response and display in the examples for this route.

Similarly to @response tag, you can provide multiple @responseFile tags along with the HTTP status code of the response:

/**
 * @responseFile responses/users.get.json
 * @responseFile 404 responses/model.not.found.json
 */
public function getUser(int $id)
{
  // ...
}

Generating responses automatically

If you don't specify an example response using any of the above means, this package will attempt to get a

response by making a request to the route (a "response call"). A few things to note about response calls:

  • They are done within a database transaction and changes are rolled back afterwards.
  • The configuration for response calls is located in the config/idoc.php. They are configured within the ['apply']['response_calls'] section for each route group, allowing you to apply different settings for different sets of routes.
  • By default, response calls are only made for GET routes, but you can configure this. Set the methods key to an array of methods or '*' to mean all methods. Leave it as an empty array to turn off response calls for that route group.
  • Parameters in URLs (example: /users/{user}, /orders/{id?}) will be replaced with '1' by default. You can configure this, however. Put the parameter names (including curly braces and question marks) as the keys and their replacements as the values in the bindings key.
  • You can configure environment variables (this is useful so you can prevent external services like notifications from being triggered). By default the APP_ENV is set to 'documentation'. You can add more variables in the env key.
  • By default, the package will generate dummy values for your documented body and query parameters and send in the request. (If you specified example values using @bodyParam or @queryParam, those will be used instead.) You can configure what headers and additional query and parameters should be sent when making the request (the headers, query, and body keys respectively).
  • By default all middlewares are enabled, but you can set the without_middleware array to specify the middlewares you prefer to disable, you can even use ['*'] to disable all.

Open-API 3.0 spec file

The generator automatically creates an Open-API 3.0 spec file, which you can import to use within any external api application.

The default base URL added to the spec file will be that found in your Laravel config/app.php file. This will likely be http://localhost. If you wish to change this setting you can directly update the url or link this config value to your environment file to make it more flexible (as shown below):

'url' => env('APP_URL', 'http://yourappdefault.app'),

If you are referring to the environment setting as shown above, then you should ensure that you have updated your .env file to set the APP_URL value as appropriate. Otherwise the default value (http://yourappdefault.app) will be used in your spec file. Example environment value:

APP_URL=http://yourapp.app

Further modification

The info file in the view folder can be further modified to add introductions and further documentation.

Credits

This software uses the following open source packages:

You may also like...

License

MIT

Comments
  • bug-fix for lumen frame work:

    bug-fix for lumen frame work:

    pull request purpose: bare repo is not working with any lumen version error: Call to undefined method Illuminate\Routing\Router::middlewareGroup() reason: middle group is not supported in lumen, lumen has it's own router

    • add laravel default public_path helper because it's not present in lumen usage IDocGeneratorCommand line 74
    • improve readme.md to define public path if needed
    • add new routes for lumen because it's totaly diffrent
    • extends service provider for lumen
    opened by phpooya 1
  • Support laravel 8?

    Support laravel 8?

    System info:

    PHP: 8.0 Laravel: 8.x

    I get some error:

    ovac/idoc v1.3.0 requires illuminate/routing 5.5.* || 5.6.* || 5.7.* || 5.8.* || ^6.0 || ^7.0 -> found illuminate/routing[v5.5.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev] b ut these were not loaded, likely because it conflicts with another require.

    opened by AGDholo 1
  • Not able to install ..Showing :No such host is known

    Not able to install ..Showing :No such host is known

    The "https://repo.packagist.org/packages.json" file could not be downloaded: php_network_getaddresses: getaddrinfo failed: No such host is known. failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known. https://repo.packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date

    opened by abdulmajidab 1
  • Side menu behavior in Chrome

    Side menu behavior in Chrome

    Redoc generated side menu disappears when scrolling down in latest version of Chrome and group expansion and collapse is inconsistent.

    This bug was already reported in redoc https://github.com/Redocly/redoc/issues/1167,

    Looks like an deprecated CDN version bug

    opened by js-moreno 0
  • removed str_random() usage since its no longer available

    removed str_random() usage since its no longer available

    Fixes the following error:

    Call to undefined function OVAC\IDoc\str_random()
    
      at /.../IDocGenerator.php:292
        288|             'boolean' => function () use ($faker) {
        289|                 return $faker->boolean();
        290|             },
        291|             'string' => function () use ($faker) {
      > 292|                 return str_random();
        293|             },
        294|             'array' => function () {
        295|                 return '[]';
        296|             },
    
    opened by pedro-santiago 0
  • Laravel 9 support

    Laravel 9 support

    Hello It's a shame that this great tool can't be used in Laravel 9. That's why I decided to make some changes so that those using Laravel 9 can benefit from this tool. The changes that have been made are:

    1. Upgrade the php version
    2. Add version 9 to illuminate/routing, illuminate/routing, illuminate/console
    opened by sharifnezhad 0
  • Properties[] and Required[] keywords do not have a value?

    Properties[] and Required[] keywords do not have a value?

    In no way I seem to be able to make idoc generate values for Properties and Required keywords in the schema of the @response content. Any indication how to do this?

    opened by ronaldwanink 0
  • IDocGeneratorCommand error when generate IDoc.

    IDocGeneratorCommand error when generate IDoc.

    After run: php artisan idoc:generate Error

    In IDocGeneratorCommand.php line 127:
                                                                          
    Class C:32:"Opis\Closure\SerializableClosure":296:{ does not exist
    
    opened by iamapinan 0
  • Group description

    Group description

    Hi,

    I would like to write a description to my endpoint group usig some like:

    /**
     * Lorem ipsum dolor, sit amet consectetur adipisicing elit. 
     * 
     * @group Lorem
     * 
     */
    

    Nowadays this description is not shown in documentation generated

    opened by js-moreno 0
Releases(v1.4.0)
Owner
Ariama Victor (A.K.A. OVAC4U)
Nigerian Ghana Based Full-Stack Developer
Ariama Victor (A.K.A. OVAC4U)
The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs

NelmioApiDocBundle The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs. Migrate from 3.x to 4.0 To migrate from

Nelmio 2.1k Jan 6, 2023
Raidbots API wrapper which incorporates existing reports and static data into your project.

Raidbots API Raidbots API wrapper which incorporates existing reports and static data into your project. Usage use Logiek\Raidbots\Client; $client =

Logiek 2 Dec 23, 2021
The Laravel documentation.

Laravel Documentation You can find the online version of the Laravel documentation at https://laravel.com/docs Contribution Guidelines If you are subm

The Laravel Framework 2.6k Dec 31, 2022
Mink documentation

Mink Documentation This repository contains the documentation for the Mink project. The rendered documentation is hosted at Read the Docs. Contribute

Mink 83 Nov 14, 2022
Simple and effective multi-format Web API Server to host your PHP API as Pragmatic REST and / or RESTful API

Luracast Restler ![Gitter](https://badges.gitter.im/Join Chat.svg) Version 3.0 Release Candidate 5 Restler is a simple and effective multi-format Web

Luracast 1.4k Dec 14, 2022
LaraBooks API - Simple API for iOS SwiftUI app tests.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Konrad Podrygalski 1 Nov 13, 2021
Jane is a set of libraries to generate Models & API Clients based on JsonSchema / OpenAPI specs

Jane is a set of libraries to generate Models & API Clients based on JsonSchema / OpenAPI specs Documentation Documentation is available at http://jan

Jane 438 Dec 18, 2022
Single file PHP script that adds a REST API to a SQL database

PHP-CRUD-API Single file PHP script that adds a REST API to a MySQL/MariaDB, PostgreSQL, SQL Server or SQLite database. NB: This is the TreeQL referen

Maurits van der Schee 3.2k Jan 8, 2023
Laravel A2Reviews Client API lets you build apps, extensions, or plugins to get reviews from the A2reviews APP.

Overview Laravel A2Reviews Client API lets you build apps, extensions or plugins to get reviews from the A2reviews APP. Including adding reviews to a

Be Duc Tai 2 Sep 26, 2021
API for flutter app in laravel with sanctum

Flutter APP Flutter: APP with auth in laravel About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe develop

Angel Flores 0 Apr 9, 2022
Open source API management platform

About Fusio is an open source API management platform which helps to build and manage REST APIs. Fusio provides all tools to quickly build an API from

Apioo 1.2k Jan 4, 2023
An open source PHP framework for the mcsrvstat.us api

MinePHP An open source PHP framework for the Minecraft Server Status API. Installation Clone the repository in the first place. git clone https://gith

null 2 May 23, 2022
The NKN open API is a blockchain-to-database parser with an easy to use interface written in PHP

The NKN open API is a blockchain-to-database parser with an easy to use interface written in PHP. We're using Laravel as our framework to provide a clean and maintainable code.

Rule110 - The NKN open source community 7 Jun 26, 2022
Official docker container of Fusio an open source API management system

Fusio docker container Official docker container of Fusio. More information about Fusio at: https://www.fusio-project.org Usage The most simple usage

Apioo 28 Dec 13, 2022
Open Source Telecommunications API Platform

A reimplementation of the open source Plivo framework on top of ReactPHP and FreeSWITCH. If you are not familiar with the legacy platform, please inspect its repository as well as the archived web resources here, here and here.

rtckit 33 Nov 25, 2022
BT Open API SDK in PHP

Mosel, a sdk package for BT open APIs This package is still under construction (july 13th 2022). Open Api are described in the Bouygues Telecom Develo

BboxLab 0 Jul 7, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
The maker bundle allows you to generate content elements, front end modules

Contao 4 maker bundle The maker bundle allows you to generate content elements, front end modules, event listener, callbacks and hooks using interacti

Contao 7 Aug 3, 2022
This bundle provides tools to build a complete GraphQL server in your Symfony App.

OverblogGraphQLBundle This Symfony bundle provides integration of GraphQL using webonyx/graphql-php and GraphQL Relay. It also supports: batching with

Webedia - Overblog 720 Dec 25, 2022