Skip to content

SpecGenerator

Viames Marino edited this page Feb 23, 2026 · 1 revision

Pair framework: SpecGenerator

Pair\Api\OpenApi\SpecGenerator builds an OpenAPI 3.1 specification from Pair CRUD resources plus optional custom endpoints.

When to use

Use SpecGenerator when you need machine-readable API docs for SDK generation, contract review, and client integration.

Constructor

$spec = new \Pair\Api\OpenApi\SpecGenerator('My API', '1.0.0');

Main methods

Metadata

  • setDescription(string $description): void
  • addContact(string $name, ?string $email = null, ?string $url = null): void
  • addLicense(string $name, ?string $url = null): void

Server/tags/security

  • addServer(string $url, string $description = ''): void
  • addTag(string $name, string $description = ''): void
  • addSecurityScheme(string $name, string $type, array $config = []): void

Paths/resources

  • addPath(string $path, string $method, array $operation): void
  • addCrudResources(CrudController $controller, string $basePath = '/api'): void

Output

  • build(): array
  • toJson(bool $pretty = true): string
  • toYaml(): string

Implementation example

use Pair\Api\OpenApi\SpecGenerator;

$spec = new SpecGenerator('Pair App API', '1.0.0');
$spec->setDescription('Public REST API');
$spec->addServer('https://api.example.com', 'Production');
$spec->addContact('API Team', 'api@example.com');
$spec->addLicense('MIT', 'https://opensource.org/licenses/MIT');
$spec->addSecurityScheme('bearerAuth', 'http', ['scheme' => 'bearer']);

// from CrudController instance
$spec->addCrudResources($apiController, '/api');

// custom endpoint
$spec->addPath('/api/auth/login', 'post', [
    'summary' => 'Login',
    'responses' => [
        '200' => ['description' => 'Success'],
        '401' => ['description' => 'Unauthorized'],
    ]
]);

$json = $spec->toJson();

Notes

  • CRUD paths are auto-generated per registered slug.
  • Components include schemas from SchemaGenerator.
  • Security schemes are added under components.securitySchemes.

Frequent usage recipes

Add multiple environments

$spec->addServer('https://api.example.com', 'Production');
$spec->addServer('https://staging-api.example.com', 'Staging');

Add bearer security globally in operations

$spec->addSecurityScheme('bearerAuth', 'http', [
    'scheme' => 'bearer',
    'bearerFormat' => 'JWT'
]);

Export to JSON and YAML

file_put_contents(APP_PATH . '/public/openapi.json', $spec->toJson(true));
file_put_contents(APP_PATH . '/public/openapi.yaml', $spec->toYaml());

Common pitfalls

  • Forgetting to include custom non-CRUD endpoints.
  • Drift between validation rules and documented request schemas.
  • Publishing specs without environment-appropriate server URLs.

See also: SchemaGenerator, CrudController, API.

Clone this wiki locally