百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
A

api-generator

> 后端框架
开源

用于 Laravel 框架的 PHP 代码生成器,完全支持 JSON-API 数据格式

326 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用于 Laravel 框架的 PHP 代码生成器,完全支持 JSON-API 数据格式

api-generator

PHP-code generator (based on OAS) for Laravel framework, with complete support of JSON-API data format

  • Getting started Demo
  • CRUD Demo
  • Relation links Demo
  • Migrations Demo
  • API docs Demo
  • Installation
    • Configuration
    • Optional settings
    • Running generator
    • Docker repo
  • Open API Types and Declarations
  • Open API Docs generator
  • Generated files content
    • Module Config
    • Controllers
    • FormRequests
    • Models
    • Routes
    • Migrations
    • Tests
  • Relationships
  • Bulk Extension
  • Query parameters
  • Security
    • Static access token
    • JWT
  • Caching
  • Soft Delete
  • Tree structures
  • Finite-state machine
  • Spell check
  • Bit mask
  • Custom SQL
  • Custom business logic
  • Regeneration

Installation via composer:

First of all - create Laravel project if you didn't do that yet:

composer create-project --prefer-dist laravel/laravel your_app

then in your project directory run:

composer require solidry/api-generator

It will automatically register Laravel ServiceProvider by adding console command api:generate (you should see it when running php artisan) and also publish "laravel-modules" provider.

Autoloading

By default Controllers, entities or repositories are not loaded automatically. You can autoload your modules using psr-4. For example :

json
{
  "autoload": {
    "psr-4": {
      "App\\": "app/",
      "Modules\\": "Modules/"
    }
  }
}

refresh changes by running:

composer dump-autoload

Optional settings

To provide Json API compatible error handler one can add ErrorHandler trait to app/Exceptions/Handler class and return return $this->renderJsonApi($request, $exception); from standard Laravel render method, complete example of Handler class will look something like this:

php
renderJsonApi($request, $exception); // method you should call to return json-api response
    }
}

As you may noticed it returns Illuminate\Http\JsonResponse Laravel object to output data appropriately e.g.:

…

The default Laravel installation has an api prefix for API routes. If you want to access generated json api routes via their prefix first ex.: /v2/article or /myshop/basket, you will need to remove the prefix from the mapApiRoutes() method in your RouteServiceProvider.

php
namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

Running generator

Run in console:

php artisan api:generate oas/openapi.yaml --migrations

This command creates the whole environment for you to proceed building complex API based on OAS/Laravel/JSON API, in particular: directories for modular app, Controllers/FormRequests/Models+Pivots to support full MVC, Routes (JSON API compatible) and even migrations to help you create RDBMS structure.

oas/openapi.yaml - file in oas directory in the root of your project, which should be prepared before or you may wish to just try by copying an example from mkdir oas && curl 'https://raw.githubusercontent.com/SoliDry/api-generator/master/tests/functional/oas/openapi.yaml' > /oas/openapi.yaml and probably rewrite it for your needs.

You can also use .json ext/format to produce the same results if required or more convenient for your environment.

Options:

--migrations is an option to create migrations (create_entityName_table) for every entity + pivots if there are ManyToMany relationships.

--regenerate use this if you need to rewrite all files generated previously. By default generated files preserved to prevent overwriting of added/modified content.

The output will look something like this:

After that u can see the following dirs and files module structure in your project:

Docker repository

Another way of installing and playing with api-generator (in sandbox fashion) is via https://github.com/SoliDry/laravel-api. Clone repository and run:

bash
docker-compose up -d

You can see Dockerfile and docker-compose.yml files there.

PS Any contributions to build a better containers are welcome.

Open API Types and Declarations

OAS (Open API Specification) was developed as merge of Swagger and RAML specs by two groups of developers (they tired of arguing with each other :smile:), thus it became quite popular and has been implemented for api-generator

…

or in json:

…

U can set multiple servers as well as multiple files into the main openapi.yaml, thus code will be generated for every server module e.g.: Modules/v2, Modules/v3, Modules/v4 and there will be other Types from different files.

Basic and custom Types are declared under

yaml
components:
  schemas:

or in json:

json
"components": {
    "schemas": {

Types ID, Type, DataObject/DataArray are special helper Types - !required

You can easily add string IDs to entities you'd like for example SID can be placed in Article entity like that id: SID - api-generator will produce migrations, relations and models respectively.

yaml
  ID:
    type: integer
    required: true
    # it will be BIGINT UNSIGNED in migration Schema if maximum > 10
    maximum: 20
  SID:
    type: string
    required: true
    maxLength: 128    
  Type:
    type: string
    required: true
    minLength: 1
    maxLength: 255
  DataObject:
    type: object
    required: true
  DataArray:
    type: array
    required: true

or in json:

json
"ID": {
    "type": "integer",
    "required": true,
    "maximum": 20
},
"SID": {
    "type": "string",
    "required": true,
    "maxLength": 128
},
"Type": {
    "type": "string",
    "required": true,
    "minLength": 1,
    "maxLength": 255
},
"DataObject": {
    "type": "object",
    "required": true
},
"DataArray": {
    "type": "array",
    "required": true
}

Special data type RelationshipsDataItem - !required

yaml
  RelationshipsDataItem:
    type: object
    properties:
      id: ID
      type: Type

or in json:

json
"RelationshipsDataItem": {
    "type": "object",
    "properties": {
        "id": "ID",
        "type": "Type"
    }
}

defined in every relationship custom type

Attributes *Attributes are defined for every custom Object ex.:

…

or in json:

…

Relationships custom type definition semantics *Relationships

yaml
  TagRelationships:
    description: Tag relationship description
    type: object
    properties:
      data:
        type: DataArray
        items:
          type: RelationshipsDataItem
json
"TagRelationships": {
    "description": "Tag relationship description",
    "type": "object",
    "properties": {
        "data": {
            "type": "DataArray",
            "items": {
                "type": "RelationshipsDataItem"
            }
        }
    }
}

Complete composite Object looks like this:

yaml
  Article:
    type: object
    properties:
      type: Type
      id: ID
      attributes: ArticleAttributes
      relationships:
        type: TagRelationships[] | TopicRelationships     
json
"Article": {
    "type": "object",
    "properties": {
        "type": "Type",
        "id": "SID",
        "attributes": "ArticleAttributes",
        "relationships": {
            "type": "TagRelationships[] | TopicRelationships"
        }
    }
}

That is all that api-generator needs to provide code structure that just works out-fo-the-box within Laravel framework, where may any business logic be applied.

To use multiple files processing add (as root element):

yaml
uses:
  topics: oas/openapi.yaml
  otherfile: oas/otherFile.yaml
  yetanother: oas/yetanother.yaml

all files will be generated as if they were one composite object.

To set default values for GET query parameters - set QueryParams like this:

…

it will be used on requests similar to: http://example.com/api/v1/article?include=tag where no params were passed.

Complete directory structure after generator will end up it`s work will be like:

…

Open API Docs generator

OAS *Controllers based documentation is generated out of the box, thus you don't need to create it manually let's see a couple examples:

All generated methods (when expanded) will look like this:

There is no magic in it at all - just look into your generated controllers there are pre-generated annotations for every method e.g.:

…

Controllers

Entity controller example:

…

Note, that U have an ability to make any ranges for varchar, integer types through minLength/maxLength and minimum/maximum respectively. For instance, integer can be set to unsigned smallint with minimum: 1 (any number > 0) and maximum: 2 (any number in article table for topic table id, see ArticleAttributes in OAS Types and Declarations) or make your own foreign key and add it to hasMany/belongsTo -> $foreignKey parameter in generated BaseModel entity.

Additionally, to specify index for particular column you can add a facets property like this:

yaml
    # regular index
    facets:
      index:
        idx_title: index            
        
    # unique key    
    facets:
      index:
        idx_url: unique             
        
    # foreign key
    facets:
      index:
        idx_fk_topic_id: foreign
        references: id
        on: topic
        onDelete: cascade
        onUpdate: cascade

to existing columns.

However, there are situations where you have to create composite indices:

yaml
      last_name:
        required: false
        type: string
        minLength: 16
        maxLength: 256
        facets:
          composite_index:
            index: ['first_name', 'last_name'] # can be unique, primary

an example for foreign key would be like:

yaml
    facets:
      composite_index:
        foreign: ['first_column', 'second_column'] 
        references: ['first_column', 'second_column']
        on: first_second
        onDelete: cascade
        onUpdate: cascade        

Tests

To provide convenient way for integration/functional testing, one can generate tests by providing --tests command option, e.g.:

bash
php artisan api:generate oas/openapi.yaml --migrations --tests

in command output you'll see the following files have been created:

bash
tests/functional/ArticleCest.php created
...
tests/functional/TagCest.php created

For more info on how to set an environment for functional tests in Laravel - see https://codeception.com/for/laravel

Relationships particular qualities

To let generator know about what

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPapiapi-generatorcode-generatorgenerator

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架