PHPackages                             zvonchuk/phalcon-openapi - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. zvonchuk/phalcon-openapi

ActiveLibrary[HTTP &amp; Networking](/categories/http)

zvonchuk/phalcon-openapi
========================

Automatic OpenAPI 3.1 spec generation for Phalcon PHP — zero annotations, convention-based inference

v1.0.0(1mo ago)30MITPHPPHP ^8.1CI passing

Since Apr 22Pushed 1mo agoCompare

[ Source](https://github.com/zvonchuk/phalcon-openapi)[ Packagist](https://packagist.org/packages/zvonchuk/phalcon-openapi)[ Docs](https://github.com/zvonchuk/phalcon-openapi)[ RSS](/packages/zvonchuk-phalcon-openapi/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

phalcon-openapi
===============

[](#phalcon-openapi)

[![Tests](https://github.com/zvonchuk/phalcon-openapi/actions/workflows/tests.yml/badge.svg)](https://github.com/zvonchuk/phalcon-openapi/actions)[![Latest Stable Version](https://camo.githubusercontent.com/852b1fdc82ee62059cd0acf21ceeb096e571eaef8ded43819472dcf0822d5609/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a766f6e6368756b2f7068616c636f6e2d6f70656e6170692e737667)](https://packagist.org/packages/zvonchuk/phalcon-openapi)[![PHP Version](https://camo.githubusercontent.com/aaeadb480e55b030afb7c63213ccf8ddd0d521166cca2f29956f37be07815a30/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7a766f6e6368756b2f7068616c636f6e2d6f70656e6170692e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/a5bab572c838410cff878c139b199ed83d0236d195caa6d336dacf49bcbb7a81/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7a766f6e6368756b2f7068616c636f6e2d6f70656e6170692e737667)](LICENSE)[![PHPStan](https://camo.githubusercontent.com/0729e562e10fac943b16dbb271b4af26488f779a33fc82cc3eef1e37a432c0b4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230352d627269676874677265656e2e737667)](https://phpstan.org/)

Automatic **OpenAPI 3.1** spec generation for Phalcon PHP applications.

Generates a complete OpenAPI spec by reading your routes, controllers, models, and DTOs — no annotations, no YAML, no manual work. Just write your code and get Swagger UI for free.

Why This Package
----------------

[](#why-this-package)

Annotation-based approachphalcon-openapiRoutesDuplicated in annotationsRead from Phalcon Router automaticallySchemasSeparate schema definitionsBuilt from your existing DTOs and ModelsValidationDocumentation onlySame attributes for docs AND runtimeStatus codesManual per-endpointConvention-based (201, 204, 422, 404)SetupCustom controller + HTMLTwo lines of codeRequirements
------------

[](#requirements)

- PHP 8.1+
- Phalcon 5.x

Installation
------------

[](#installation)

```
composer require zvonchuk/phalcon-openapi
```

Quick Start
-----------

[](#quick-start)

```
use PhalconOpenApi\OpenApiModule;

$module = new OpenApiModule([
    'title'   => 'My API',
    'version' => '1.0.0',
]);
$module->registerServices($di);
```

Two endpoints are registered automatically:

- `GET /api/openapi.json` — OpenAPI 3.1 JSON spec
- `GET /api/docs` — Swagger UI

How It Works
------------

[](#how-it-works)

The package automatically reads:

- **Router** — all registered routes, HTTP methods, path patterns
- **Model MetaData** — column types, nullable, primary keys
- **Reflection** — controller action parameters, return types, docblocks
- **PHP 8 Attributes** — optional tags, hidden endpoints, extra responses, security

### Convention-Based Inference

[](#convention-based-inference)

Zero annotations needed for standard CRUD:

```
class UserController extends ApiController
{
    // GET /users → 200 with array of User, operationId: listUsers
    public function listAction(int $page = 1, int $limit = 20) { }

    // POST /users → 201 Created + 422 Validation Error, operationId: createUser
    public function createAction(CreateUserRequest $body) { }

    // GET /users/{id} → 200 + 404 Not Found, operationId: getUser
    public function getAction(int $id) { }

    // DELETE /users/{id} → 204 No Content + 404, operationId: deleteUser
    public function deleteAction(int $id) { }
}
```

The spec generator infers:

- **Status codes**: `create` → 201, `delete` → 204, others → 200
- **422 Validation Error**: auto-added when endpoint has a DTO body parameter
- **404 Not Found**: auto-added when route has path parameters
- **operationId**: generated from controller + action name
- **Tags**: from controller name (`UserController` → `Users`)
- **Schemas**: from Phalcon Model metadata or DTO class properties

Attributes Reference
--------------------

[](#attributes-reference)

All attributes are optional — use only when conventions aren't enough.

### Endpoint Attributes

[](#endpoint-attributes)

```
use PhalconOpenApi\Attribute\{ApiTag, ApiIgnore, ApiResponse, ApiDescription, ApiSecurity, ApiPaginated};

#[ApiTag('Users')]              // Group endpoints (class or method level)
#[ApiSecurity('bearerAuth')]    // Require auth (class or method level)
class UserController extends ApiController
{
    #[ApiDescription(
        summary: 'List all users',
        description: 'Returns a paginated list of users with optional filtering'
    )]
    #[ApiPaginated]             // Wraps response in {data, total, page, per_page}
    public function listAction(int $page = 1) { }

    #[ApiIgnore]                // Hide from spec
    public function internalAction() { }

    #[ApiResponse(409, ConflictResponse::class)]  // Extra response code
    public function createAction(CreateUserRequest $body) { }
}
```

### Validation Attributes

[](#validation-attributes)

Used for both **runtime validation** (via `DtoValidator`) and **OpenAPI schema generation**:

```
use PhalconOpenApi\Attribute\{Email, Min, Max, StringLength, Format, Pattern, Enum, Url, NotBlank};

class CreateUserRequest
{
    #[NotBlank]
    #[StringLength(min: 1, max: 255)]
    public string $name;

    #[Email]
    public string $email;

    public ?string $phone = null;       // nullable → type: ["string", "null"]

    #[Min(1), Max(150)]
    public int $age;

    #[Enum(['active', 'inactive'])]
    public string $status = 'active';   // → enum in OpenAPI schema

    #[Url]
    public ?string $website = null;     // → format: uri in schema

    #[Format('date')]
    public ?string $birthDate = null;   // → format: date in schema

    #[Pattern('/^\+\d{10,15}$/')]       // PCRE delimiters stripped for OpenAPI
    public ?string $mobile = null;
}
```

AttributeValidatesOpenAPI Schema`#[Email]`Valid email format`format: email``#[StringLength(min: 1, max: 255)]`String length bounds`minLength`, `maxLength``#[Min(1)]`, `#[Max(150)]`Numeric range`minimum`, `maximum``#[Enum(['a', 'b'])]`Allowed values`enum: ["a", "b"]``#[Url]`Valid URL`format: uri``#[NotBlank]`Rejects whitespace-only`minLength: 1``#[Format('date')]`Date/datetime/uuid/uri`format: date``#[Pattern('/regex/')]`PCRE regex match`pattern: regex`### Nested DTOs and Typed Arrays

[](#nested-dtos-and-typed-arrays)

Nested objects are validated recursively with dot-notation error paths:

```
class CreateOrderRequest
{
    #[StringLength(min: 1)]
    public string $orderNumber;

    public AddressDto $shippingAddress;  // → $ref + recursive validation

    /** @var OrderItemDto[] */
    public array $items = [];            // → array with $ref + per-item validation
}

class AddressDto
{
    #[NotBlank]
    public string $street;

    #[NotBlank]
    public string $city;

    #[Pattern('/^\d{5}$/')]
    public string $zip;
}
```

Validation errors for nested objects use dot-notation:

```
{
    "code": 422,
    "message": "Validation failed",
    "errors": [
        "shippingAddress.city is required",
        "items[0].zip must match pattern /^\\d{5}$/"
    ]
}
```

Security Configuration
----------------------

[](#security-configuration)

```
$module = new OpenApiModule([
    'title'   => 'My API',
    'version' => '1.0.0',
    'security' => [
        'bearerAuth' => [
            'type'         => 'http',
            'scheme'       => 'bearer',
            'bearerFormat' => 'JWT',
        ],
    ],
]);
```

Then annotate controllers or methods with `#[ApiSecurity('bearerAuth')]`.

Base Controller
---------------

[](#base-controller)

Extend `ApiController` for automatic JSON body parsing, DTO validation, and convenience helpers:

```
use PhalconOpenApi\ApiController;

class UserController extends ApiController
{
    public function getAction(int $id)
    {
        $user = User::findFirst($id);
        if (!$user) {
            return $this->notFound('User not found');
        }
        return $this->json($user);
    }

    public function createAction(CreateUserRequest $body)
    {
        // $body is already validated and hydrated automatically
        $user = new User();
        $user->assign((array) $body);
        $user->save();
        return $this->json($user, 201);
    }
}
```

Configuration Options
---------------------

[](#configuration-options)

```
$module = new OpenApiModule([
    'title'          => 'My API',           // required
    'version'        => '1.0.0',            // required
    'description'    => 'API description',  // optional
    'modelNamespace' => 'App\\Models',      // enables convention-based model inference
    'servers'        => [                   // optional
        ['url' => 'https://api.example.com'],
    ],
    'security'       => [ /* ... */ ],      // optional, see Security section
]);
```

Demo Application
----------------

[](#demo-application)

See [phalcon-openapi-demo](https://github.com/zvonchuk/phalcon-openapi-demo) for a complete working example with Docker and CRUD controllers.

Running Tests
-------------

[](#running-tests)

```
vendor/bin/phpunit
```

License
-------

[](#license)

MIT

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance90

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

49d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8db6ca2224db0a8bbd9cc281466ceb7c6f1f6dd29d550d65fef42268c4c9de27?d=identicon)[zvonchuk](/maintainers/zvonchuk)

---

Top Contributors

[![zvonchuk](https://avatars.githubusercontent.com/u/33892061?v=4)](https://github.com/zvonchuk "zvonchuk (2 commits)")

---

Tags

openapiphalconphpswaggerapirestdocumentationswaggeropenapiphalcon

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/zvonchuk-phalcon-openapi/health.svg)

```
[![Health](https://phpackages.com/badges/zvonchuk-phalcon-openapi/health.svg)](https://phpackages.com/packages/zvonchuk-phalcon-openapi)
```

###  Alternatives

[vyuldashev/laravel-openapi

Generate OpenAPI Specification for Laravel Applications

4621.2M](/packages/vyuldashev-laravel-openapi)[tartanlegrand/laravel-openapi

Generate OpenAPI Specification for Laravel Applications

38201.0k2](/packages/tartanlegrand-laravel-openapi)[vanderlee/swaggergen

Generate Swagger/OpenAPI documentation from simple PHPdoc-like comments in PHP source code.

42129.9k3](/packages/vanderlee-swaggergen)[api-platform/laravel

API Platform support for Laravel

59156.3k10](/packages/api-platform-laravel)[noitran/opendox

OpenApi(Swagger) 3.0 package for Lumen 5.5+ and Laravel 5.5+ with REDOC UI and SwaggerUI 3

2214.2k](/packages/noitran-opendox)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
