Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Apidoc Generator Laravel Package

mpociot/laravel-apidoc-generator

Generate API docs automatically from your existing Laravel, Lumen, or Dingo routes. Run php artisan apidoc:generate to produce up-to-date documentation from code and routes, with configurable output via an apidoc.php config file.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev mpociot/laravel-apidoc-generator
    

    Publish the config file:

    php artisan vendor:publish --provider="Mpociot\ApiDoc\ApiDocGeneratorServiceProvider" --tag=apidoc-config
    
  2. Generate Documentation:

    php artisan apidoc:generate
    

    Outputs to storage/apidoc/index.html by default.

  3. First Use Case: Document a simple GET endpoint in a controller:

    /**
     * @group Users
     * Get a user by ID
     *
     * @queryParam id integer The user ID
     * @return \App\Http\Resources\UserResource
     */
    public function show($id)
    {
        return User::findOrFail($id);
    }
    

Where to Look First

  • Config File: config/apidoc.php – Customize output paths, default groups, and strategies.
  • Generated Output: storage/apidoc/index.html – View the interactive API docs.
  • Documentation: Beyond Code Docs – Official guides and examples.

Implementation Patterns

Core Workflow

  1. Annotate Controllers: Use docblocks (@group, @queryParam, @bodyParam, @urlParam, @return) to define API behavior.

    /**
     * @group Products
     * @bodyParam name string The product name (required)
     * @bodyParam price float The product price
     * @return \App\Http\Resources\ProductResource
     */
    public function store(Request $request)
    {
        // ...
    }
    
  2. Generate Docs: Run php artisan apidoc:generate to compile annotations into interactive HTML docs.

  3. Integrate with CI/CD: Add to your deployment pipeline to auto-update docs on changes:

    # .github/workflows/docs.yml
    jobs:
      generate-docs:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v2
          - run: composer install
          - run: php artisan apidoc:generate
          - uses: actions/upload-artifact@v2
            with:
              name: apidoc
              path: storage/apidoc/
    

Advanced Patterns

  • Dynamic Groups: Use plugins to dynamically assign groups based on route attributes (e.g., middleware):

    // In a custom strategy
    public function __invoke(Route $route, ReflectionClass $controller, ReflectionMethod $method, array $routeRules, array $context = [])
    {
        if ($route->hasMiddleware('auth:admin')) {
            return ['groupName' => 'Admin'];
        }
        return null;
    }
    
  • Postman Integration: Enable Postman collection generation in config/apidoc.php:

    'postman' => [
        'enabled' => true,
        'output' => 'storage/apidoc/collection.json',
    ],
    
  • Custom Templates: Override Blade templates in resources/views/vendor/apidoc/ to modify the HTML output.

  • Testing Strategies: Mock responses in tests to avoid real API calls:

    // In a test
    $this->app->bind(\Mpociot\ApiDoc\Extracting\Strategies\Responses\ResponseCalls::class, function () {
        return new class {
            public function __invoke(Route $route, ReflectionClass $controller, ReflectionMethod $method, array $routeRules, array $context = [])
            {
                return [['content' => '{"test": true}', 'status' => 200]];
            }
        };
    });
    

Gotchas and Tips

Pitfalls

  1. DocBlock Parsing Quirks:

    • Whitespace Sensitivity: Ensure no extra spaces or lines break docblock parsing.
      // ❌ Fails (extra line)
      /**
       * @group Users
       *
       */
      
      // ✅ Works
      /**
       * @group Users
       */
      
    • Nested Annotations: Avoid malformed nested tags (e.g., @queryParam inside @group).
  2. Circular Dependencies:

    • If routes reference each other (e.g., User resource with nested Address routes), ensure all related controllers are annotated to avoid missing docs.
  3. Dynamic Routes:

    • Routes with dynamic segments (e.g., {id}) may not render correctly in the UI. Use @urlParam to clarify:
      /**
       * @urlParam id integer The user ID
       */
      public function show($id) { ... }
      
  4. Postman Collection Issues:

    • Authentication: Ensure your Postman collection includes auth headers if your API requires them.
    • Base URL: Set base_url in config/apidoc.php to avoid relative path issues:
      'postman' => [
          'base_url' => 'https://api.yourdomain.com',
      ],
      
  5. Performance:

    • Large APIs: Generating docs for thousands of routes can be slow. Exclude unused routes in config/apidoc.php:
      'routes' => [
          'exclude' => [
              'admin/*',
              'web/*',
          ],
      ],
      

Debugging Tips

  1. Check Generated Markdown: Outputs to storage/apidoc/markdown/index.md. Inspect this file to debug rendering issues.

  2. Enable Verbose Logging: Run with -v to see strategy execution:

    php artisan apidoc:generate -v
    
  3. Validate DocBlocks: Use PHPStan or Psalm to catch syntax errors in docblocks early.

  4. Test Strategies Isolated: Create a custom command to test a single strategy:

    // app/Console/Commands/TestStrategy.php
    public function handle()
    {
        $route = app()->router->getRoutes()->getByName('user.show');
        $strategy = new \App\Strategies\CustomStrategy();
        $result = $strategy($route, new ReflectionClass(UserController::class), new ReflectionMethod(UserController::class, 'show'), []);
        dd($result);
    }
    

Extension Points

  1. Custom Strategies:

    • Extend \Mpociot\ApiDoc\Extracting\Strategies\Strategy to add logic (e.g., auto-generate createdAt query params).
    • Register in config/apidoc.php under the appropriate stage.
  2. Override Templates: Copy vendor/mpociot/laravel-apidoc-generator/resources/views/ to resources/views/vendor/apidoc/ to customize the HTML output.

  3. Hook into Generation: Use events to modify the process:

    // In a service provider
    public function boot()
    {
        \Mpociot\ApiDoc\Events\Generating::subscribe(function ($event) {
            $event->markdown .= "\n## Custom Section";
        });
    }
    
  4. Add Sample Data: Use the ParamsHelper trait to generate realistic test data:

    use Mpociot\ApiDoc\Extracting\ParamsHelper;
    
    class CustomStrategy extends Strategy
    {
        use ParamsHelper;
    
        public function __invoke(Route $route, ReflectionClass $controller, ReflectionMethod $method, array $routeRules, array $context = [])
        {
            return [
                'userId' => $this->generateDummyValue('integer', ['min' => 1]),
            ];
        }
    }
    
  5. Conditional Documentation: Skip documenting routes based on environment or features:

    public function __invoke(Route $route, ReflectionClass $controller, ReflectionMethod $method, array $routeRules, array $context = [])
    {
        if (app()->environment('local')) {
            return null; // Skip in local env
        }
        return ['metadata' => ['title' => 'Prod-only Endpoint']];
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor