{"id":14155477,"url":"https://github.com/cebe/yii2-openapi","last_synced_at":"2025-10-01T02:31:23.334Z","repository":{"id":43673232,"uuid":"154310166","full_name":"cebe/yii2-openapi","owner":"cebe","description":"REST API application generator for Yii2, openapi 3.0 YAML -\u003e Yii2","archived":true,"fork":false,"pushed_at":"2024-06-04T15:27:09.000Z","size":1327,"stargazers_count":131,"open_issues_count":25,"forks_count":21,"subscribers_count":10,"default_branch":"master","last_synced_at":"2024-09-22T22:01:57.932Z","etag":null,"topics":["hacktoberfest","openapi3","php","rest-api","scaffolding","yii","yii2"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cebe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-23T10:39:18.000Z","updated_at":"2024-07-16T20:11:58.000Z","dependencies_parsed_at":"2023-12-14T13:38:30.610Z","dependency_job_id":"b7b52abb-bfea-4faf-aa1f-c8975d0e8d1e","html_url":"https://github.com/cebe/yii2-openapi","commit_stats":{"total_commits":489,"total_committers":8,"mean_commits":61.125,"dds":0.5255623721881391,"last_synced_commit":"e5b445904399c26c2a88ebd8af768576333dc156"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cebe%2Fyii2-openapi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cebe%2Fyii2-openapi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cebe%2Fyii2-openapi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cebe%2Fyii2-openapi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cebe","download_url":"https://codeload.github.com/cebe/yii2-openapi/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219875269,"owners_count":16554660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","openapi3","php","rest-api","scaffolding","yii","yii2"],"created_at":"2024-08-17T08:03:26.152Z","updated_at":"2025-10-01T02:31:17.613Z","avatar_url":"https://github.com/cebe.png","language":"PHP","readme":"# yii2-openapi\n\n\u003e\n\u003e **This repository has been moved to \u003chttps://github.com/php-openapi/yii2-openapi\u003e.**  \n\u003e **Please use the new package `php-openapi/yii2-openapi` instead.**\n\u003e\n\nREST API application generator for Yii2, openapi 3.0 YAML -\u003e Yii2.\n\nBase on [Gii, the Yii Framework Code Generator](https://www.yiiframework.com/extension/yiisoft/yii2-gii).\n\n[![Latest Stable Version](https://poser.pugx.org/cebe/yii2-openapi/v/stable)](https://packagist.org/packages/cebe/yii2-openapi)\n[![Latest Alpha Version](https://poser.pugx.org/cebe/yii2-openapi/v/unstable)](https://packagist.org/packages/cebe/yii2-openapi)\n[![Total Downloads](https://poser.pugx.org/cebe/yii2-openapi/downloads)](https://packagist.org/packages/cebe/yii2-openapi)\n[![License](https://poser.pugx.org/cebe/yii2-openapi/license)](https://packagist.org/packages/cebe/yii2-openapi)\n![yii2-openapi](https://github.com/cebe/yii2-openapi/workflows/yii2-openapi/badge.svg?branch=wip)\n\n## TLDR; what is this?\n\nA code generator for OpenAPI and Yii Framework based PHP API application.\n\nInput: [OpenAPI 3.0 YAML or JSON](https://github.com/OAI/OpenAPI-Specification#the-openapi-specification) (via [cebe/php-openapi](https://github.com/cebe/php-openapi))\n\nOutput: Yii Framework Application with Controllers, Models, database schema\n\n\n## Features\n\nCurrently available features:\n\n- Generate Path mappings, **Controllers** and Actions **for API Endpoints**. CRUD Endpoints are ready-to-use, other Endpoints are generated as abstract functions that need to be implemented\n- Generate **Models** and validation based on OpenAPI Schema\n- Generate **Database Schema** from OpenAPI Schema\n- Generates **Database Migrations** for schema changes\n- Provide **Dummy Data** via Faker for development\n\n## Requirements\n\n- PHP 7.1 or higher (works fine with PHP 8)\n\n\n## Install\n\n    composer require php-openapi/yii2-openapi:^2.0@beta\n\n## Usage\n\nYou can use this package in your existing application or start a new project using the\n[yii2-app-api](https://github.com/cebe/yii2-app-api) application template.\nFor usage of the template, see instructions in the template repo readme.\n\nIn your existing Yii application config (works for console as well as web):\n\n```php\n\u003c?php\n$config = [\n    // ... this is your application config ...\n];\n\nif (YII_ENV_DEV) {\n    // enable Gii module\n    $config['bootstrap'][] = 'gii';\n    $config['modules']['gii'] = [\n        'class' =\u003e \\yii\\gii\\Module::class,\n        'generators' =\u003e [\n            // add ApiGenerator to Gii module\n            'api' =\u003e \\cebe\\yii2openapi\\generator\\ApiGenerator::class,\n\n            // --------- OR ---------\n            // to disable generation of migrations files or with default config change\n            'api' =\u003e [\n              'class' =\u003e \\cebe\\yii2openapi\\generator\\ApiGenerator::class,\n              'generateMigrations' =\u003e false, # this config can also be applied in CLI command\n            ],\n        ],\n    ];\n}\n\nreturn $config;\n```\n\nTo use the web generator, open `index.php?r=gii` and select the `REST API Generator`.\n\nOn console you can run the generator with `./yii gii/api --openApiPath=@app/openapi.yaml`. Where `@app/openapi.yaml` should be the absolute path to your OpenAPI spec file. This can be JSON as well as YAML (see also [cebe/php-openapi](https://github.com/cebe/php-openapi/) for supported formats).\n\nRun `./yii gii/api --help` for all options. Example: Disable generation of migrations files `./yii gii/api --generateMigrations=0`\n\nSee [Petstore example](https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.0/petstore.yaml) for example OpenAPI spec.\n\n\n## OpenAPI extensions\n\nThis library understands the following extensions to the OpenAPI spec:\n\n### `x-faker`\n\nYou may specify custom PHP code for generating fake data for a property:\n\n```yaml\n    Post:\n      properties:\n        id:\n          type: integer\n        tags:\n          type: array\n          items:\n            type: string\n          example: ['one', 'two']\n          x-faker: \"$faker-\u003erandomElements(['one', 'two', 'three', 'four'])\"\n```\n\nTo avoid generating faker code for particular model attribute, use value `false`:\n\n```yaml\n    Post:\n      properties:\n        age:\n          type: integer\n          x-faker: false\n```\n\nUsing in reference with `allOf`:\n\n```yaml\n    Invoice:\n      type: object\n      required:\n        - id\n      properties:\n        id:\n          type: integer\n\n    Order:\n      type: object\n      required:\n        - id\n      properties:\n        id:\n          type: integer\n        invoice:\n          allOf:\n            - $ref: '#/components/schemas/Invoice'\n            - x-faker: false\n```\n\n### `x-table`\n\nSpecify the table name for a Schema that defines a model which is stored in the database.\nYou can generate non-db model based on \\yii\\base\\Model without migrations by setting `x-table: false`\n\n### `x-pk`\n\nExplicitly specify primary key name for table, if it is different from \"id\" \n\n```yaml\n    Post:\n      x-table: posts\n      x-pk: uid\n      properties:\n        uid:\n           type: integer\n        title:\n           type: string\n```\n\n### `x-db-type`\n\nExplicitly specify the database type for a column. (MUST contain only real DB type! (`json`, `jsonb`, `uuid`, `varchar` etc.)).\nIf `x-db-type` is set to `false`, property will be processed as virtual;\nIt will be added in model as public property, but skipped for migrations generation.\n\nExample values of `x-db-type` are:\n\n - `false` (boolean false)\n - as string and its value can be like:\n     - text\n     - text[]\n     - INTEGER PRIMARY KEY AUTO_INCREMENT\n     - decimal(12,4)\n     - json\n     - varchar\n     - VARCHAR\n     - SMALLINT UNSIGNED ZEROFILL\n     - MEDIUMINT(10) UNSIGNED ZEROFILL COMMENT \"comment\" (note the double quotes here)\n\nSuch values are not allowed:\n   - `int null default null after low_price` (null and default will be handled by `nullable` and `default` keys respectively)\n   - MEDIUMINT(10) UNSIGNED ZEROFILL NULL DEFAULT '7' COMMENT 'comment' AFTER `seti`, ADD INDEX `t` (`w`)\n\nIf `enum` and `x-db-type` both are provided then for database column schema (migrations), only `x-db-type` will be considered ignoring `enum`.\n\n### `x-indexes`\n\nSpecify table indexes\n\n```yaml\n    Post:\n      x-table: posts\n      x-indexes:\n          - 'visible,publish_date'\n          - 'unique:title' #for unique attributes also unique validation check will be added\n          - 'gist:metadata' #for postgres will generate index using GIST index type\n      properties:\n        id:\n           type: integer\n           x-db-type: INTEGER PRIMARY KEY AUTO_INCREMENT\n        title:\n           type: string\n        visible:\n            type: boolean\n        publish_date:\n            type: string\n            format: date\n        metadata:\n           type: object\n           x-db-type: JSON\n           default: '{}' \n```\n\n### `x-db-default-expression`\n\nAbility to provide default value by database expression\n\n```yaml\ncreated_at:\n  readOnly: true\n  type: string\n  format: datetime\n  x-db-type: datetime\n  nullable: false\n  x-db-default-expression: current_timestamp()\n```\n\nNote: If both `default` and `x-db-default-expression` are present then `default` will be considered.\n\n```yaml\ncreated_at:\n  readOnly: true\n  type: string\n  format: datetime\n  x-db-type: datetime\n  nullable: false\n  x-db-default-expression: current_timestamp() # this will be ignored\n  default: \"2011-11-11\" # this will be considered\n```\n\nAlso see: https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html\n\n### `x-fk-on-delete`\n\nAllow to set foreign key constraint in migrations for ON DELETE event of row in database table. Example:\n\n```yaml\n  components:\n    schemas:\n      User:\n        type: object\n        description: x on-x (update|delete) foreign key constraint\n        properties:\n          id:\n            type: integer\n          name:\n            type: string\n      Post:\n        type: object\n        description: x on-x (update|delete) foreign key constraint\n        properties:\n          id:\n            type: integer\n          title:\n            type: string\n          user:\n            allOf:\n              - $ref: '#/components/schemas/User'\n              - x-fk-on-update: CASCADE\n          user_2:\n            allOf:\n              - $ref: '#/components/schemas/User'\n              - x-fk-on-update: CASCADE\n              - x-fk-on-delete: SET NULL\n          user_3:\n            allOf:\n              - $ref: '#/components/schemas/User'\n              - x-fk-on-delete: SET NULL\n          user_4:\n            $ref: '#/components/schemas/User' # without any constraints\n```\n\n### `x-fk-on-update`\n\nAllow to set foreign key constraint in migrations for ON UPDATE event of row in database table. For example, see above section for `x-fk-on-delete`.\n\n### `x-fk-column-name`\n\nProvide custom database table column name in case of relationship column. This will not reflect in models relations, faker etc. Example:\n\n```yaml\n  components:\n    schemas:\n      Webhook:\n        type: object\n        description: example for x-fk-column-name\n        properties:\n          id:\n            type: integer\n          name:\n            type: string\n          user:\n            $ref: '../openapi.yaml#/components/schemas/User' # this will automatically create `user_id` column\n          redelivery_of:\n            allOf:\n              - $ref: '../openapi.yaml#/components/schemas/Delivery'\n              # this will automatically create `redelivery_of_id` column, but to avoid that use below extension\n              - x-fk-column-name: redelivery_of # this will create `redelivery_of` column instead of `redelivery_of_id`\n```\n\n## Many-to-Many relation definition\n\nThere are two ways for define many-to-many relations:\n\n### Simple many-to-many without junction model\n\n   - property name for many-to-many relation should be equal lower-cased, pluralized related schema name\n     \n   - referenced schema should contains mirrored reference to current schema\n     \n   - migration for junction table can be generated automatically - table name should be [pluralized, lower-cased\n schema_name1]2[pluralized, lower-cased schema name2], in alphabetical order;\n For example, for schemas Post and Tag - table should be posts2tags, for schemas Post and Attachement - table should\n  be attachments2posts\n  \n```\nPost:\n  properties:\n  ...\n    tags:\n      type: array\n      items:\n        $ref: '#/components/schemas/Tag'\n\nTag:\n  properties:\n  ...\n    posts:\n      type: array\n      items:\n        $ref: '#/components/schemas/Post'\n```\n  \n### Many-to-many with junction model\n\nThis way allowed creating multiple many-to-many relations between to models \n\n- define junction schema with all necessary attributes. There are only one important requirement - the junction\n schema name\n must be started with prefix 'junction_' (This prefix will be used internally only and\n will be trimmed before table and model generation)\n \n```\n# Model TeamMembers with table team_members will be generated with columns team_id, user_id and role\njunction_TeamMembers:\n   team:\n      $ref: '#/components/schemas/Team'\n   user:\n      $ref: '#/components/schemas/User'\n   role:\n     type: string\n```\n- Both many-to-many related schemas must have properties with reference to \"junction_*\" schema. These properties will be\n used as relation names \n\n```\nTeam:\n  properties:\n  ...\n     team_members:\n       type: array\n       items:\n         $ref: '#/components/schemas/junction_TeamMembers'\n\nUser:\n  properties:\n  ...\n    memberships: #You absolutely free with naming for relationship attributes\n      type: array\n      items:\n        $ref: '#/components/schemas/junction_TeamMembers'\n```\n  \n - see both examples here [tests/specs/many2many.yaml](tests/specs/many2many.yaml)\n \n\n## Handling of `NOT NULL` constraints\n\n`NOT NULL` in DB migrations is determined by `nullable` and `required` properties of the OpenAPI schema.\ne.g. attribute = 'my_property'.\n\n- If you define attribute neither \"required\" nor via \"nullable\", then it is by default `NULL`:\n\n```yaml\n  ExampleSchema:\n    properties:\n      my_property:\n        type: string\n```\n\n- If you define attribute in \"required\", then it is `NOT NULL`\n\n```yaml\n  ExampleSchema:\n    required:\n     - my_property\n    properties:\n      my_property:\n        type: string\n```\n\n- If you define attribute via \"nullable\", then it overrides \"required\", e.g. allow `NULL` in this case:\n\n```yaml\n  ExampleSchema:\n    required:\n      - my_property\n    properties:\n      my_property:\n        type: string\n        nullable: true\n```\n\n- If you define attribute via \"nullable\", then it overrides \"required\", e.g. `NOT NULL` in this case:\n\n```yaml\n  test_table:\n    required:\n    properties:\n      my_property:\n        type: string\n        nullable: false\n```\n\n## Handling of `enum` (#enum)\nIt works on all 3 DB: MySQL, MariaDb and PgSQL.\n\n ```yaml\n  test_table:\n    properties:\n      my_property:\n        enum:\n          - one\n          - two\n          - three\n```\n\nNote: Changes in enum values are not very simple. For Mysql and Mariadb, migrations will be generated but in many cases custom modification in it are required. For Pgsql migrations for change in enum values will not be generated. It should be handled manually.\n\nIt will be ignored for database column schema (migrations) if `x-db-type` is provided.\n\n## Handling of `numeric` (#numeric, #MariaDb)\n\nprecision-default = 10\nscale-default = 2\n\n- You can define attribute like \"numeric(precision,scale)\":\n ```yaml\n  test_table:\n    properties:\n      my_property:\n        x-db-type: decimal(12,4)\n```\nDB-Result = decimal(12,4)\n\n- You can define attribute like \"numeric(precision)\" with default scale-default = 2:\n ```yaml\n  test_table:\n    properties:\n      my_property:\n        x-db-type: decimal(12)\n```\nDB-Result = decimal(12,2)\n\n- You can define attribute like \"numeric\" with precision-default = 10 and scale-default = 2:\n ```yaml\n  test_table:\n    properties:\n      my_property:\n        x-db-type: decimal\n```\nDB-Result = decimal(10,2)\n\n## Handling of `timestamp` database column data type\n\nIf field is defined as\n\n```yaml\ncreated_at:\n    type: string\n    format: date-time # or datetime\n    example: '2020-03-14T21:42:17Z'\n    readOnly: true\n```\n\nthen database type selected will be `timestamp`. This is by design. If `datetime` data type is needed, use `x-db-type` as\n\n```yaml\ncreated_at:\n    type: string\n    format: date-time # or datetime\n    example: '2020-03-14T21:42:17Z'\n    x-db-type: datetime\n    readOnly: true\n```\n\n## Assumptions\n\nWhen generating code from an OpenAPI description there are many possible ways to achive a fitting result.\nThus there are some assumptions and limitations that are currently applied to make this work.\nHere is a (possibly incomplete) list:\n\n- The current implementation works best with OpenAPI description that follows the [JSON:API](https://jsonapi.org/) guidelines.\n  - The request and response format/schema is currently not extracted from OpenAPI schema and may need to be adjusted manually if it does not follow JSON:API\n- column/field/property with name `id` is considered as Primary Key by this library and it is automatically handled by DB/Yii; so remove it from validation `rules()`\n  - other fields can currently be used as primary keys using the `x-pk` OpenAPI extension (see below) but it may not be work correctly in all cases, please report bugs if you find them.\n\nOther things to keep in mind:\n\n### Adding columns to existing tables\n\nWhen adding new fields in the API models, new migrations will be generated to add these fields to the table.\nFor a project that is already in production, it should be considered to adjust the generated migration to add default\nvalues for existing data records.\n\nOne case where this is important is the addition of a new column with `NOT NULL` contraint, which does not provide a default value.\nSuch a migration will fail when the table is not empty:\n\n```php\n$this-\u003eaddColumn('{{%company}}', 'name', $this-\u003estring(128)-\u003enotNull());\n```\n\nFails on a PostgreSQL database with\n\n\u003e add column name string(128) NOT NULL to table {{%company}} ...Exception: SQLSTATE[23502]: Not null violation: 7 ERROR:  column \"name\" contains null values\n\nThe solution would be to create the column, allowing NULL, set the value to a default and add the null constraint later.\n\n```php\n$this-\u003eaddColumn('{{%company}}', 'name', $this-\u003estring(128)-\u003enull());\n$this-\u003eupdate('{{%company}}', ['name' =\u003e 'No name']);\n$this-\u003ealterColumn('{{%company}}', 'name', $this-\u003estring(128)-\u003enotNull());\n```\n\n## Screenshots\n\nGii Generator Form:\n\n![Gii Generator Form](doc/screenshot-form.png)\n\nGenerated files:\n\n![Gii Generated Files](doc/screenshot-files.png)\n\n\n# Development\n\nTo contribute or play around, steps to set up this project up locally are in [CONTRIBUTING.md](./CONTRIBUTING.md).\n\n\n# Support\n\n**Need help with your API project?**\n\nProfessional support, consulting as well as software development services are available:\n\nhttps://www.cebe.cc/en/contact\n\nDevelopment of this library is sponsored by [cebe.:cloud: \"Your Professional Deployment Platform\"](https://cebe.cloud).\n","funding_links":[],"categories":["rest-api"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcebe%2Fyii2-openapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcebe%2Fyii2-openapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcebe%2Fyii2-openapi/lists"}