> ## 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.

# Advanced Usage

> Master API type filtering, environments, templates, caching, and programmatic generation

This guide covers advanced features for customizing and optimizing your documentation generation workflow.

## API Type Filtering

API types allow you to segment your routes into logical groups (e.g., admin, mobile, public). Each API type can have its own prefix, folder structure, and enable/disable toggle.

### Configuring API Types

Define API types in `config/openapi.php`:

```php theme={null}
'api_types' => [
    'admin' => [
        'prefix' => 'admin',
        'folder_name' => 'API Admin',
        'enabled' => true,
    ],
    'mobile' => [
        'prefix' => 'mobile',
        'folder_name' => 'API Mobile',
        'enabled' => true,
    ],
    'site' => [
        'prefix' => 'api',
        'folder_name' => 'API Public',
        'enabled' => false,  // Disabled types are excluded
    ],
],
```

<Note>
  Routes are matched by the `prefix` value. A route like `/admin/users` matches the `admin` API type.
</Note>

### Filtering at Runtime

<Tabs>
  <Tab title="CLI">
    ```bash theme={null}
    # Single API type
    php artisan openapi:generate --api-type=admin

    # Multiple API types
    php artisan openapi:generate --api-type=admin --api-type=mobile

    # All formats for specific types
    php artisan openapi:generate --all --api-type=admin --api-type=mobile
    ```

    Filenames include the API type suffix:

    * `openapi-admin.json`
    * `postman-mobile.json`
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    # Single API type
    curl "http://localhost:8000/documentation/openapi.json?api_type=admin"

    # Multiple API types (comma-separated)
    curl "http://localhost:8000/documentation/openapi.json?api_type=admin,mobile"
    ```
  </Tab>

  <Tab title="Programmatic">
    ```php theme={null}
    use Ronu\OpenApiGenerator\Services\OpenApiServices;

    $service = app(OpenApiServices::class);
    $service->setApiTypeFilter(['admin', 'mobile']);

    $spec = $service->generate(
        useCache: true,
        apiTypes: ['admin', 'mobile'],
        environment: 'production',
        generationType: 'openapi'
    );
    ```
  </Tab>
</Tabs>

### Legacy API Type Aliases

<Warning>
  The package normalizes the legacy alias `movile` to `mobile` for backwards compatibility. You'll see a deprecation warning if you use it:

  ```text theme={null}
  ⚠️ API type 'movile' is deprecated. Use 'mobile' instead.
  ```

  Update your commands and scripts to use `mobile`.
</Warning>

## Environment Management

Environments define base URLs, authentication tokens, and other variables for different deployment stages (local, staging, production).

### Configuring Environments

Define environments in `config/openapi.php`:

```php theme={null}
'environments' => [
    // Base environment used during generation
    'base' => [
        'app_name' => env('APP_NAME', 'Laravel API'),
        'app_url' => env('APP_URL', 'http://localhost:8000'),
    ],
    
    // Sub-environments for Postman/Insomnia
    'sub_environments' => [
        'artisan' => [
            'app_url' => 'http://localhost:8000',
        ],
        'local' => [
            'app_url' => 'http://localhost:8000',
        ],
        'production' => [
            'app_url' => 'https://api.example.com',
        ],
    ],
    
    // Tracking variables merged into all sub-environments
    'tracking_variables' => [
        'api_token' => '',
        'device_id' => '',
    ],
],
```

### Selecting Environments

<Steps>
  <Step title="Via CLI">
    ```bash theme={null}
    # Default (artisan environment)
    php artisan openapi:generate

    # Specify environment
    php artisan openapi:generate --environment=production
    php artisan openapi:generate --with-postman --environment=local
    ```

    If the specified environment doesn't exist, the generator falls back to `artisan`:

    ```text theme={null}
    ⚠️ Unknown environment 'staging', using 'artisan' as default
    ```
  </Step>

  <Step title="Via HTTP">
    ```bash theme={null}
    curl "http://localhost:8000/documentation/postman?environment=production"
    ```
  </Step>

  <Step title="Environment Files">
    The generator creates separate environment files for Postman:

    * `postman-env-artisan.json`
    * `postman-env-local.json`
    * `postman-env-production.json`

    Each file includes base + tracking variables merged with sub-environment values.
  </Step>
</Steps>

<Tip>
  Tracking variables like `api_token` are automatically included in all environments. Define them once in `tracking_variables` instead of repeating them in each sub-environment.
</Tip>

## Caching

The generator caches OpenAPI specifications to improve performance for large applications.

### Cache Configuration

```php theme={null}
'cache' => [
    'enabled' => true,
    'ttl' => 3600,  // Time-to-live in seconds (1 hour)
],
```

### Disabling Cache

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

  ```php Programmatic theme={null}
  $spec = $service->generate(
      useCache: false,
      apiTypes: null,
      environment: 'production',
      generationType: 'openapi'
  );
  ```
</CodeGroup>

<Warning>
  **When to disable caching:**

  * During active development with frequent route changes
  * After adding or modifying FormRequest validation rules
  * In queue workers that should always regenerate fresh documentation
  * When testing documentation accuracy

  Cached output becomes stale when you add routes, modify request validation, or update custom endpoint documentation.
</Warning>

### Cache Keys

The generator builds cache keys from:

* API type filters
* Environment name
* Generation type (openapi, postman, insomnia)

This means filtering by different API types creates separate cache entries.

## Custom Output Paths

Override the default output directory:

<Tabs>
  <Tab title="Single File">
    ```bash theme={null}
    php artisan openapi:generate --output=/custom/path/openapi.json
    ```

    Specifies the exact file path for the OpenAPI specification.
  </Tab>

  <Tab title="Directory Override">
    Change the base output directory in `config/openapi.php`:

    ```php theme={null}
    'output_path' => storage_path('app/public/openapi'),
    ```

    Or use an absolute path:

    ```php theme={null}
    'output_path' => '/var/www/public/docs',
    ```
  </Tab>
</Tabs>

<Note>
  The generator automatically creates parent directories if they don't exist.
</Note>

## Template-Driven Documentation

The template system allows you to standardize descriptions, summaries, and request/response documentation across CRUD operations.

### Enabling Templates

Publish and enable template processing:

```bash theme={null}
php artisan vendor:publish --tag=openapi-templates
```

Configure in `config/openapi-templates.php`:

```php theme={null}
return [
    'enabled' => true,
    
    'paths' => [
        'generic' => resource_path('openapi/templates/generic'),
        'custom' => resource_path('openapi/templates/custom'),
    ],
    
    'generic_templates' => [
        'list' => 'list.json',
        'show' => 'show.json',
        'create' => 'create.json',
        'update' => 'update.json',
        'delete' => 'delete.json',
    ],
];
```

### Template Structure

Generic templates define reusable documentation for standard CRUD actions:

<Accordion title="Example: list.json">
  ```json theme={null}
  {
    "summary": "List {{entity_plural}}",
    "description": "Retrieve a paginated list of {{entity_plural}}.",
    "parameters": [
      {
        "name": "page",
        "in": "query",
        "schema": {"type": "integer"},
        "description": "Page number for pagination"
      },
      {
        "name": "per_page",
        "in": "query",
        "schema": {"type": "integer"},
        "description": "Items per page"
      }
    ]
  }
  ```
</Accordion>

<Accordion title="Example: show.json">
  ```json theme={null}
  {
    "summary": "Get {{entity_singular}}",
    "description": "Retrieve details for a specific {{entity_singular}}.",
    "parameters": [
      {
        "name": "id",
        "in": "path",
        "required": true,
        "schema": {"type": "integer"},
        "description": "{{entity_singular}} ID"
      }
    ]
  }
  ```
</Accordion>

### Custom Endpoint Documentation

For non-CRUD endpoints, define custom documentation in `config/openapi-docs.php`:

```php theme={null}
'custom_endpoints' => [
    'api-apps.rotate' => [
        'summary' => 'Rotate API Key',
        'description' => 'Generates a new API key for the application.',
        'request_fields' => [
            'reason' => 'Optional reason for key rotation',
        ],
        'response_description' => 'Returns the new API key and revocation timestamp.',
    ],
    'users.export' => [
        'summary' => 'Export Users',
        'description' => 'Generates a CSV export of filtered users.',
        'request_fields' => [
            'format' => 'Export format: csv, xlsx, or json',
            'filters' => 'Array of filter conditions',
        ],
    ],
],
```

<Tip>
  Use the pattern `entity.action` for keys. The generator matches these against route names like `api-apps.rotate` or `users.export`.
</Tip>

### Template Processing Flow

<Steps>
  <Step title="Route Introspection">
    The generator extracts route metadata: path, methods, parameters, FormRequests.
  </Step>

  <Step title="Template Selection">
    * Check for custom endpoint documentation by route name
    * If not found, match CRUD action (list, show, create, update, delete)
    * Load corresponding generic template
  </Step>

  <Step title="Placeholder Replacement">
    Replace placeholders like `{{entity_singular}}` and `{{entity_plural}}` with actual values.
  </Step>

  <Step title="Merge with Metadata">
    Combine template content with extracted FormRequest validation rules and model properties.
  </Step>
</Steps>

<Warning>
  **Template Validation**

  Invalid JSON in template files causes generation to fail. Enable output validation during debugging:

  ```php theme={null}
  'rendering' => [
      'validate_output' => true,
  ],
  ```

  This adds extra validation but slows generation.
</Warning>

## Excluding Routes

Prevent specific routes from appearing in documentation:

```php theme={null}
'exclude_routes' => [
    'horizon.*',
    'telescope.*',
    'sanctum.*',
    '_debugbar.*',
    'internal.*',
],
```

Patterns support wildcards. Routes matching any pattern are excluded from all generated documentation.

## Programmatic Generation Advanced

For complex use cases, you can directly access generation services:

```php theme={null}
use Ronu\OpenApiGenerator\Services\OpenApiServices;
use Ronu\OpenApiGenerator\Services\PostmanCollectionGenerator;
use Ronu\OpenApiGenerator\Services\InsomniaWorkspaceGenerator;
use Ronu\OpenApiGenerator\Services\EnvironmentGenerator;

// Generate OpenAPI with full control
$openApiService = app(OpenApiServices::class);
$openApiService->setApiTypeFilter(['admin']);
$spec = $openApiService->generate(
    useCache: false,
    apiTypes: ['admin'],
    environment: 'production',
    generationType: 'openapi'
);

// Generate Postman collection from spec
$postmanGen = app(PostmanCollectionGenerator::class);
$collection = $postmanGen->generate($spec, 'production', ['admin']);

// Generate Insomnia workspace from spec
$insomniaGen = app(InsomniaWorkspaceGenerator::class);
$workspace = $insomniaGen->generate($spec, 'production', ['admin']);

// Generate environment files
$envGen = app(EnvironmentGenerator::class);
$postmanEnv = $envGen->generatePostman('production');
$insomniaEnvs = $envGen->generateInsomnia('production');
```

<Accordion title="Service Responsibilities">
  **OpenApiServices**

  * Route introspection and filtering
  * Caching
  * OpenAPI specification assembly

  **PostmanCollectionGenerator**

  * Converts OpenAPI spec to Postman Collection v2.1 format
  * Embeds environment variables

  **InsomniaWorkspaceGenerator**

  * Converts OpenAPI spec to Insomnia v4 format
  * Creates workspace with spec, collection, and test tabs

  **EnvironmentGenerator**

  * Merges base + tracking + sub-environment variables
  * Generates environment files for Postman and Insomnia
</Accordion>

## Next Steps

<CardGroup cols={2}>
  <Card title="Common Scenarios" icon="lightbulb" href="/guides/common-scenarios">
    Real-world examples including team workflows and CI/CD integration.
  </Card>

  <Card title="Edge Cases" icon="triangle-exclamation" href="/guides/edge-cases">
    Handling config caching, concurrent generation, and multi-tenant deployments.
  </Card>
</CardGroup>
