PHP-code generator for Laravel framework, with complete support of JSON-API data format
PHP-code generator for Laravel framework, with complete support of JSON-API data format
PHP-code generator (based on OAS) for Laravel framework, with complete support of JSON-API data format
First of all - create Laravel project if you didn't do that yet:
composer create-project --prefer-dist laravel/laravel your_appthen in your project directory run:
composer require solidry/api-generatorIt 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.
By default Controllers, entities or repositories are not loaded automatically. You can autoload your modules using psr-4.
For example :
{
"autoload": {
"psr-4": {
"App\\": "app/",
"Modules\\": "Modules/"
}
}
}refresh changes by running:
composer dump-autoloadTo 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:
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.
namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}Run in console:
php artisan api:generate oas/openapi.yaml --migrationsThis 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:
Another way of installing and playing with api-generator (in sandbox fashion) is via https://github.com/SoliDry/laravel-api. Clone repository and run:
docker-compose up -dYou can see Dockerfile and docker-compose.yml files there.
PS Any contributions to build a better containers are welcome.
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
components:
schemas:or in 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.
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: trueor in 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
RelationshipsDataItem:
type: object
properties:
id: ID
type: Typeor in 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
TagRelationships:
description: Tag relationship description
type: object
properties:
data:
type: DataArray
items:
type: RelationshipsDataItem"TagRelationships": {
"description": "Tag relationship description",
"type": "object",
"properties": {
"data": {
"type": "DataArray",
"items": {
"type": "RelationshipsDataItem"
}
}
}
}Complete composite Object looks like this:
Article:
type: object
properties:
type: Type
id: ID
attributes: ArticleAttributes
relationships:
type: TagRelationships[] | TopicRelationships "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):
uses:
topics: oas/openapi.yaml
otherfile: oas/otherFile.yaml
yetanother: oas/yetanother.yamlall 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:
…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.:
…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:
# 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: cascadeto existing columns.
However, there are situations where you have to create composite indices:
last_name:
required: false
type: string
minLength: 16
maxLength: 256
facets:
composite_index:
index: ['first_name', 'last_name'] # can be unique, primaryan example for foreign key would be like:
facets:
composite_index:
foreign: ['first_column', 'second_column']
references: ['first_column', 'second_column']
on: first_second
onDelete: cascade
onUpdate: cascade To provide convenient way for integration/functional testing, one can generate tests by providing --tests command option, e.g.:
php artisan api:generate oas/openapi.yaml --migrations --testsin command output you'll see the following files have been created:
tests/functional/ArticleCest.php created
...
tests/functional/TagCest.php createdFor more info on how to set an environment for functional tests in Laravel - see https://codeception.com/for/laravel
To let generator know about what
No open issues yet, or sync has not completed.