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

# Public API

> Complete reference for the OpenApiGenerator facade and service methods

## Overview

The Laravel OpenAPI Generator provides a clean programmatic API for generating OpenAPI specifications, Postman collections, and Insomnia workspaces. You can use either the facade or inject the service directly.

## Facade

The package registers a facade for convenient access:

```php theme={null}
use Ronu\OpenApiGenerator\Facades\OpenApiGenerator;
```

### Facade Accessor

The facade resolves to the `Ronu\OpenApiGenerator\OpenApiGenerator` service class.

**Location:** `src/Facades/OpenApiGenerator.php:10`

```php theme={null}
protected static function getFacadeAccessor(): string
{
    return OpenApiGeneratorService::class;
}
```

***

## Service Class: OpenApiGenerator

The main service class provides four public methods for generating specifications.

**Location:** `src/OpenApiGenerator.php`

### generate()

Generate a specification in any supported format.

**Signature:**

```php theme={null}
public function generate(
    bool $useCache = true,
    ?array $apiTypes = null,
    ?string $environment = null,
    string $format = 'openapi'
): array
```

**Parameters:**

<ParamField path="useCache" type="bool" default="true">
  Enable or disable cache for generation. When `true`, results are cached based on the cache configuration.
</ParamField>

<ParamField path="apiTypes" type="array|null" default="null">
  Filter by specific API types. Pass an array of type keys (e.g., `['api', 'mobile']`). When `null`, all enabled API types are included.
</ParamField>

<ParamField path="environment" type="string|null" default="null">
  Environment name to apply (e.g., `'artisan'`, `'local'`, `'production'`). When `null`, uses the default environment from configuration.
</ParamField>

<ParamField path="format" type="string" default="'openapi'">
  Output format: `'openapi'`, `'postman'`, or `'insomnia'`.
</ParamField>

**Returns:** `array` - The generated specification structure.

**Example:**

```php theme={null}
use Ronu\OpenApiGenerator\Facades\OpenApiGenerator;

// Generate OpenAPI spec for all API types
$spec = OpenApiGenerator::generate();

// Generate for specific API types with custom environment
$spec = OpenApiGenerator::generate(
    useCache: false,
    apiTypes: ['api', 'mobile'],
    environment: 'production',
    format: 'openapi'
);
```

***

### generateOpenApi()

Convenience method for generating OpenAPI 3.0.3 specifications.

**Signature:**

```php theme={null}
public function generateOpenApi(
    bool $useCache = true,
    ?array $apiTypes = null,
    ?string $environment = null
): array
```

**Parameters:**

<ParamField path="useCache" type="bool" default="true">
  Enable or disable cache for generation.
</ParamField>

<ParamField path="apiTypes" type="array|null" default="null">
  Filter by specific API types.
</ParamField>

<ParamField path="environment" type="string|null" default="null">
  Environment name to apply.
</ParamField>

**Returns:** `array` - OpenAPI 3.0.3 specification.

**Implementation:**

This method internally calls `generate()` with `format = 'openapi'`.

**Location:** `src/OpenApiGenerator.php:22-28`

**Example:**

```php theme={null}
use Ronu\OpenApiGenerator\Facades\OpenApiGenerator;

// Generate OpenAPI spec
$openapi = OpenApiGenerator::generateOpenApi();

// With filtering
$adminApi = OpenApiGenerator::generateOpenApi(
    apiTypes: ['admin'],
    environment: 'production'
);
```

***

### generatePostman()

Generate a Postman Collection (v2.1 format).

**Signature:**

```php theme={null}
public function generatePostman(
    bool $useCache = true,
    ?array $apiTypes = null,
    ?string $environment = null
): array
```

**Parameters:**

<ParamField path="useCache" type="bool" default="true">
  Enable or disable cache for generation.
</ParamField>

<ParamField path="apiTypes" type="array|null" default="null">
  Filter by specific API types.
</ParamField>

<ParamField path="environment" type="string|null" default="null">
  Environment name to apply for base URL and variables.
</ParamField>

**Returns:** `array` - Postman Collection JSON structure.

**Implementation:**

This method internally calls `generate()` with `format = 'postman'`.

**Location:** `src/OpenApiGenerator.php:30-36`

**Example:**

```php theme={null}
use Ronu\OpenApiGenerator\Facades\OpenApiGenerator;

// Generate Postman collection
$collection = OpenApiGenerator::generatePostman();

// For specific API with environment
$collection = OpenApiGenerator::generatePostman(
    apiTypes: ['mobile'],
    environment: 'artisan'
);

// Export to file
file_put_contents(
    'postman-collection.json',
    json_encode($collection, JSON_PRETTY_PRINT)
);
```

***

### generateInsomnia()

Generate an Insomnia Workspace (v4 format).

**Signature:**

```php theme={null}
public function generateInsomnia(
    bool $useCache = true,
    ?array $apiTypes = null,
    ?string $environment = null
): array
```

**Parameters:**

<ParamField path="useCache" type="bool" default="true">
  Enable or disable cache for generation.
</ParamField>

<ParamField path="apiTypes" type="array|null" default="null">
  Filter by specific API types.
</ParamField>

<ParamField path="environment" type="string|null" default="null">
  Environment name to apply for base URL and variables.
</ParamField>

**Returns:** `array` - Insomnia Workspace JSON structure.

**Implementation:**

This method internally calls `generate()` with `format = 'insomnia'`.

**Location:** `src/OpenApiGenerator.php:38-44`

**Example:**

```php theme={null}
use Ronu\OpenApiGenerator\Facades\OpenApiGenerator;

// Generate Insomnia workspace
$workspace = OpenApiGenerator::generateInsomnia();

// For admin API
$workspace = OpenApiGenerator::generateInsomnia(
    apiTypes: ['admin'],
    environment: 'local'
);

// Export to file
file_put_contents(
    'insomnia-workspace.json',
    json_encode($workspace, JSON_PRETTY_PRINT)
);
```

***

## Dependency Injection

You can also inject the service directly into your controllers or services:

```php theme={null}
use Ronu\OpenApiGenerator\OpenApiGenerator;

class DocumentationController extends Controller
{
    public function __construct(
        private readonly OpenApiGenerator $generator
    ) {}

    public function export()
    {
        $spec = $this->generator->generateOpenApi(
            apiTypes: ['api'],
            environment: 'production'
        );

        return response()->json($spec);
    }
}
```

***

## Service Provider

The package is auto-discovered via Laravel's package discovery.

**Provider:** `Ronu\OpenApiGenerator\Providers\OpenApiGeneratorServiceProvider`

**Responsibilities:**

* Registers `OpenApiServices` and `OpenApiGenerator` as singletons
* Publishes configuration files
* Registers Artisan commands
* Registers HTTP routes (if enabled)

**Configuration Publishing:**

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

***

## HTTP Controller (Optional)

If HTTP routes are enabled (`openapi.routes.enabled = true`), the package provides a controller for web access.

**Controller:** `Ronu\OpenApiGenerator\Controllers\OpenApiController`

**Available HTTP Endpoints:**

| Route                                   | Method | Description                       |
| --------------------------------------- | ------ | --------------------------------- |
| `/documentation/openapi.{format}`       | GET    | Generate OpenAPI spec (JSON/YAML) |
| `/documentation/postman`                | GET    | Generate Postman collection       |
| `/documentation/insomnia`               | GET    | Generate Insomnia workspace       |
| `/documentation/environments/{format?}` | GET    | Get all environments              |

**Query Parameters:**

* `api_type` - Comma-separated list of API types
* `environment` - Environment name

**Example HTTP Usage:**

```bash theme={null}
# Get OpenAPI spec for mobile API
curl "http://localhost:8000/documentation/openapi.json?api_type=mobile"

# Get Postman collection for admin API in production
curl "http://localhost:8000/documentation/postman?api_type=admin&environment=production"

# Get all environments (Postman format)
curl "http://localhost:8000/documentation/environments/postman"
```

***

## Return Value Structure

### OpenAPI Format

Returns an OpenAPI 3.0.3 compliant specification:

<ResponseField name="openapi" type="string">
  OpenAPI version (`3.0.3`)
</ResponseField>

<ResponseField name="info" type="object">
  API metadata (title, version, description, contact, license)
</ResponseField>

<ResponseField name="servers" type="array">
  Array of server objects with URLs and descriptions
</ResponseField>

<ResponseField name="paths" type="object">
  All API endpoints with operations (GET, POST, etc.)
</ResponseField>

<ResponseField name="tags" type="array">
  Resource grouping tags
</ResponseField>

<ResponseField name="components" type="object">
  Reusable schemas and security definitions
</ResponseField>

### Postman Format

Returns a Postman Collection v2.1 structure with:

* Collection metadata
* Folders grouped by module
* Pre-request scripts for token management
* Tests for response validation
* Variable references

### Insomnia Format

Returns an Insomnia v4 workspace with:

* Workspace metadata
* Request groups
* Multiple environments (base + artisan + local + production)
* Request chaining via response variables
* Automated tests

***

## Error Handling

All methods may throw the following exceptions:

<Note>
  See the [Exceptions](/api-reference/exceptions) page for detailed error handling documentation.
</Note>

**Common Exceptions:**

* `InvalidArgumentException` - Invalid API type or environment name
* `Exception` - General generation errors (invalid configuration, missing templates)

**Example with Error Handling:**

```php theme={null}
use Ronu\OpenApiGenerator\Facades\OpenApiGenerator;

try {
    $spec = OpenApiGenerator::generate(
        apiTypes: ['invalid-type']
    );
} catch (\InvalidArgumentException $e) {
    // Handle invalid API type
    logger()->error('Invalid API type', ['error' => $e->getMessage()]);
} catch (\Exception $e) {
    // Handle other errors
    logger()->error('Generation failed', ['error' => $e->getMessage()]);
}
```

***

## Cache Management

The service respects the cache configuration in `config/openapi.php`:

```php theme={null}
'cache' => [
    'enabled' => true,
    'ttl' => 3600, // 1 hour
    'key_prefix' => 'openapi_spec_',
],
```

**Clearing Cache Programmatically:**

The `OpenApiServices` class provides a cache clearing method:

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

$service = app(OpenApiServices::class);
$service->clearCache();
```

**Clearing Cache via CLI:**

```bash theme={null}
# Clear all Laravel cache (includes OpenAPI cache)
php artisan cache:clear

# Generate fresh spec without cache
php artisan openapi:generate --no-cache
```

***

## Related Documentation

<CardGroup cols={2}>
  <Card title="Artisan Commands" icon="terminal" href="/api-reference/artisan-commands">
    CLI command reference
  </Card>

  <Card title="Configuration" icon="gear" href="/configuration/reference">
    Configure API types and environments
  </Card>

  <Card title="Exceptions" icon="triangle-exclamation" href="/api-reference/exceptions">
    Error handling guide
  </Card>

  <Card title="HTTP Routes" icon="globe" href="/guides/basic-usage">
    Configure web endpoints
  </Card>
</CardGroup>
