> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/charlietyn/openapi-generator/llms.txt
> Use this file to discover all available pages before exploring further.

# Common Issues

> Solutions to frequently encountered problems when using Laravel OpenAPI Generator

This guide covers common issues you may encounter when generating OpenAPI documentation and provides actionable solutions.

## Invalid API Type Parameter

<Warning>
  **Error Message**: `Unknown or disabled API types: {type}. Available types: api, site, mobile, admin`

  **HTTP Response**: `422 Unprocessable Entity`
</Warning>

### Cause

The requested API type is either:

* Not defined in `config/openapi.php`
* Disabled in the `api_types` configuration array
* Misspelled in the command or query parameter

### Solution

<Steps>
  <Step title="Check your configuration">
    Open `config/openapi.php` and verify the `api_types` array:

    ```php theme={null}
    'api_types' => [
        'api' => [
            'enabled' => true,
            'label' => 'Public API',
        ],
        'admin' => [
            'enabled' => true,  // Make sure this is true
            'label' => 'Admin API',
        ],
    ],
    ```
  </Step>

  <Step title="Enable the API type">
    Set `enabled` to `true` for the API type you want to use.
  </Step>

  <Step title="Clear config cache">
    If you're using config caching, clear it:

    ```bash theme={null}
    php artisan config:clear
    ```
  </Step>

  <Step title="Regenerate documentation">
    ```bash theme={null}
    php artisan openapi:generate --api-type=admin
    ```
  </Step>
</Steps>

<Note>
  The legacy API type `movile` is automatically converted to `mobile`, but you should update your code to use `mobile` directly.
</Note>

***

## No Routes Found

<Warning>
  **Message**: `⚠️  No routes found matching the specified filters`
</Warning>

### Cause

Route filtering has excluded all routes. This can happen when:

* API type filters remove all matching routes
* Route exclusion patterns are too broad
* No routes are registered with the specified API type

### Solution

<Accordion title="Review route exclusions">
  Check your `config/openapi.php` for overly aggressive exclusion patterns:

  ```php theme={null}
  'exclude_routes' => [
      'admin.*',      // Excludes all admin routes
      'api/internal', // Excludes internal API routes
      '_debugbar',
      'sanctum.*',
  ],
  ```

  **Action**: Remove or refine patterns that might be excluding routes you want to document.
</Accordion>

<Accordion title="Verify API type filters">
  If using `--api-type`, ensure your routes are tagged with that API type:

  ```php theme={null}
  // In your route file or controller
  Route::get('/users', [UserController::class, 'index'])
      ->middleware(['api'])
      ->defaults('apiType', 'api');  // Must match filter
  ```

  **Try without filters** to see all routes:

  ```bash theme={null}
  php artisan openapi:generate  # No --api-type flag
  ```
</Accordion>

<Accordion title="Check route registration">
  Verify routes are actually registered:

  ```bash theme={null}
  php artisan route:list
  ```

  Look for routes that should be documented but might be missing the proper middleware or metadata.
</Accordion>

***

## HTTP 500 When Accessing Documentation Endpoint

<Warning>
  **Error**: `Failed to generate specification`

  **HTTP Status**: `500 Internal Server Error`
</Warning>

### Cause

Common causes include:

* Invalid JSON in template files
* Syntax errors in custom templates
* Exceptions during route introspection
* Memory limits exceeded with large route sets

### Solution

<Steps>
  <Step title="Run generation via CLI">
    The CLI provides full error output:

    ```bash theme={null}
    php artisan openapi:generate
    ```

    This will show the complete stack trace and error message.
  </Step>

  <Step title="Validate JSON templates">
    Check all templates in `resources/openapi/templates/`:

    ```bash theme={null}
    # Validate each JSON file
    php -r "json_decode(file_get_contents('resources/openapi/templates/openapi.json'));"
    ```

    Look for:

    * Missing commas
    * Trailing commas
    * Unclosed brackets
    * Invalid placeholder syntax
  </Step>

  <Step title="Enable detailed logging">
    Set your app to debug mode temporarily:

    ```env theme={null}
    APP_DEBUG=true
    LOG_LEVEL=debug
    ```

    Then check `storage/logs/laravel.log` for detailed errors.
  </Step>

  <Step title="Test with minimal routes">
    Temporarily exclude most routes to isolate the problem:

    ```php theme={null}
    'exclude_routes' => [
        '*',  // Exclude everything
    ],
    ```

    Then gradually add routes back to identify which one causes the error.
  </Step>
</Steps>

<Tip>
  For production environments, serve pre-generated static files instead of generating on-demand:

  ```bash theme={null}
  php artisan openapi:generate --output=public/api-docs/openapi.json
  ```

  Then serve the static file instead of using the HTTP generation endpoint.
</Tip>

***

## Placeholder Values Not Updating

<Warning>
  **Symptom**: Changes to `.env` values (like `APP_NAME`, `APP_URL`) don't appear in generated documentation
</Warning>

### Cause

Laravel's config cache is enabled, and some values are read using `env()` at runtime instead of from cached config.

### Solution

<Steps>
  <Step title="Clear config cache">
    ```bash theme={null}
    php artisan config:clear
    ```
  </Step>

  <Step title="Clear OpenAPI cache">
    ```bash theme={null}
    php artisan openapi:generate --no-cache
    ```

    Or generate without cache:

    ```bash theme={null}
    php artisan openapi:generate --no-cache
    ```
  </Step>

  <Step title="Prefer config over env()">
    Instead of changing `.env` values, override config values in `config/openapi.php`:

    ```php theme={null}
    'info' => [
        'title' => 'My Custom API Title',  // Direct value
        'version' => config('app.version'),  // From config, not env
    ],
    ```
  </Step>

  <Step title="Regenerate documentation">
    ```bash theme={null}
    php artisan openapi:generate
    ```
  </Step>
</Steps>

<Note>
  **Best Practice**: When using `config:cache` in production, always set values in config files rather than relying on runtime `env()` calls.
</Note>

***

## Concurrent Generation File Corruption

<Warning>
  **Symptom**: Partially written or inconsistent JSON/YAML files in `storage/app/public/openapi`
</Warning>

### Cause

Multiple workers or processes running `openapi:generate` simultaneously write to the same output files.

### Solution

<Accordion title="Use unique output paths">
  When running generation jobs in parallel, specify unique output files:

  ```bash theme={null}
  php artisan openapi:generate --api-type=api --output=storage/temp/openapi-api-{$timestamp}.json
  php artisan openapi:generate --api-type=mobile --output=storage/temp/openapi-mobile-{$timestamp}.json
  ```
</Accordion>

<Accordion title="Implement command locking">
  Use Laravel's command locking to prevent concurrent execution:

  ```php theme={null}
  // In a custom command that wraps openapi:generate
  public function handle()
  {
      $this->mutex->execute(function () {
          $this->call('openapi:generate', ['--all' => true]);
      });
  }
  ```
</Accordion>

<Accordion title="Use queue serialization">
  If running generation in queued jobs, use the `SerializesModels` trait and ensure jobs run one at a time:

  ```php theme={null}
  dispatch(new GenerateOpenApiJob())->onQueue('documentation');

  // Configure worker to process one job at a time
  php artisan queue:work --queue=documentation --max-jobs=1
  ```
</Accordion>

***

## Template JSON Parsing Failures

<Warning>
  **Error**: `Template not found` or `Failed to read template` or `is not valid JSON`
</Warning>

### Cause

Invalid JSON syntax or missing template files in `resources/openapi/templates/`.

### Solution

<Steps>
  <Step title="Verify template exists">
    Check that the template file exists:

    ```bash theme={null}
    ls -la resources/openapi/templates/
    ```

    Required templates:

    * `openapi.json`
    * `postman.json`
    * `insomnia.json`
  </Step>

  <Step title="Validate JSON syntax">
    Use a JSON validator:

    ```bash theme={null}
    cat resources/openapi/templates/openapi.json | jq .
    ```

    Common issues:

    * Trailing commas: `"key": "value",}` ❌
    * Missing quotes: `{key: "value"}` ❌
    * Unclosed brackets: `{"key": "value"` ❌
  </Step>

  <Step title="Enable validation in config">
    For debugging, enable output validation:

    ```php theme={null}
    // config/openapi-templates.php
    'rendering' => [
        'validate_output' => true,  // Enable validation
    ],
    ```
  </Step>

  <Step title="Test with default templates">
    Temporarily restore default templates from the package:

    ```bash theme={null}
    php artisan vendor:publish --tag=openapi-templates --force
    ```
  </Step>
</Steps>

***

## Large Route Sets Causing Timeouts

<Warning>
  **Symptom**: HTTP requests to `/documentation/openapi.json` timeout or return 500 errors
</Warning>

### Cause

Generating documentation for hundreds of routes with complex FormRequest validation can exceed PHP execution time limits.

### Solution

<Accordion title="Use CLI generation and serve static files">
  Generate documentation offline and serve pre-built files:

  ```bash theme={null}
  php artisan openapi:generate --output=public/api-docs/openapi.json
  ```

  Then configure your web server to serve the static file instead of the HTTP endpoint.
</Accordion>

<Accordion title="Increase PHP execution time">
  For the HTTP endpoint, increase time limits:

  ```php theme={null}
  // In OpenApiController or middleware
  set_time_limit(300); // 5 minutes
  ini_set('max_execution_time', 300);
  ```
</Accordion>

<Accordion title="Use API type filters">
  Reduce the number of routes processed per request:

  ```bash theme={null}
  # Generate separate files for each API type
  php artisan openapi:generate --api-type=api
  php artisan openapi:generate --api-type=admin
  php artisan openapi:generate --api-type=mobile
  ```
</Accordion>

<Accordion title="Optimize route exclusions">
  Exclude routes that don't need documentation:

  ```php theme={null}
  'exclude_routes' => [
      'debugbar.*',
      'sanctum.*',
      'telescope.*',
      'horizon.*',
      '_ignition.*',
      'admin/internal/*',
  ],
  ```
</Accordion>

***

## Rate Limiting or Auth Blocking Documentation Routes

<Warning>
  **HTTP Status**: `401 Unauthorized`, `403 Forbidden`, or `429 Too Many Requests`
</Warning>

### Cause

The middleware stack for documentation routes includes authentication or rate limiting:

```php theme={null}
'routes' => [
    'middleware' => ['web', 'auth:sanctum', 'throttle:60,1'],  // ❌ Problematic
],
```

### Solution

<Steps>
  <Step title="Use dedicated middleware stack">
    ```php theme={null}
    'routes' => [
        'enabled' => true,
        'middleware' => ['web'],  // Minimal middleware
        'prefix' => 'documentation',
    ],
    ```
  </Step>

  <Step title="Create custom middleware for docs">
    ```php theme={null}
    // app/Http/Middleware/AllowDocsAccess.php
    public function handle($request, Closure $next)
    {
        // Add your custom auth logic
        if (app()->environment('production')) {
            // Require API key or IP whitelist
            if (!$this->isAuthorized($request)) {
                abort(403);
            }
        }
        
        return $next($request);
    }
    ```

    ```php theme={null}
    // config/openapi.php
    'routes' => [
        'middleware' => ['web', AllowDocsAccess::class],
    ],
    ```
  </Step>

  <Step title="Disable HTTP routes entirely">
    Generate and serve static files instead:

    ```php theme={null}
    'routes' => [
        'enabled' => false,  // Disable HTTP generation
    ],
    ```

    ```bash theme={null}
    php artisan openapi:generate --output=public/docs/openapi.json
    ```
  </Step>
</Steps>

***

## Stale Cache in Long-Running Workers

<Warning>
  **Symptom**: Queue workers serve old documentation that doesn't reflect recent route changes
</Warning>

### Cause

The OpenAPI cache is enabled and has a long TTL, causing workers to serve outdated specs.

### Solution

<Accordion title="Disable cache for queue jobs">
  ```php theme={null}
  // In your queued job
  public function handle(OpenApiServices $generator)
  {
      $spec = $generator->generate(
          useCache: false,  // Always regenerate
          apiTypes: ['api'],
          environment: 'production'
      );
  }
  ```

  Or via CLI:

  ```bash theme={null}
  php artisan openapi:generate --no-cache
  ```
</Accordion>

<Accordion title="Reduce cache TTL">
  ```php theme={null}
  // config/openapi.php
  'cache' => [
      'enabled' => true,
      'ttl' => 300,  // 5 minutes instead of hours
  ],
  ```
</Accordion>

<Accordion title="Clear cache after deployments">
  Add cache clearing to your deployment script:

  ```bash theme={null}
  # In deploy.sh or similar
  php artisan openapi:generate --no-cache
  php artisan cache:clear
  php artisan queue:restart
  ```
</Accordion>

***

## Getting Help

<Tip>
  If you're still experiencing issues:

  1. **Enable verbose output**:
     ```bash theme={null}
     php artisan openapi:generate -vvv
     ```

  2. **Check logs**:
     * `storage/logs/laravel.log`
     * Laravel Telescope (if installed)

  3. **Report issues** with:
     * Laravel version
     * Package version
     * Full error message
     * Configuration (sanitized)
</Tip>
