GithubHelp home page GithubHelp logo

cebe / yii2-app-api Goto Github PK

View Code? Open in Web Editor NEW
105.0 8.0 11.0 224 KB

OpenAPI Spec to API in 3, 2, 1... done!

License: MIT License

PHP 81.15% Makefile 17.23% Dockerfile 1.62%
openapi openapi3 api yii2 yii2-application-template hacktoberfest

yii2-app-api's Introduction

yii2-app-api

OpenAPI Spec to API in 3, 2, 1... done!

Yii Framework Application Template for quickly building API-first applications.

Based on yii2-openapi (code generator) and php-openapi (specification reader and validator).

Latest Stable Version Total Downloads License

Demo

asciicast

Overview

This application template does not contain any useful code, it only provides the directory structure for your API project. All the code is generated from an OpenAPI API description file.

When working with this template you follow the API Design-First Approach. So to get started building an API with this application template you need an API description first. If you don't have one yet, you might want to check the following resources first:

If you have an OpenAPI description, you can continue with the next steps:

  1. Setup
  2. Generate Code

More Docs and Guides can be found in /docs.

Setup

There are two different ways:

  • PHP directly on your machine
  • Using Docker

PHP directly

Having PHP and a database server installed on your machine, you can run the following commands:

composer create-project cebe/yii2-app-api my-api
cd my-api
cp env.php.dist env.php
cp config/components-ENV.local.php config/components-dev.local.php

You need to adjust config/components-dev.local.php to configure your database connection.

After that, run make start and make stop to control the PHP webservers for API and backend.

You may use XDEBUGW=1 to enable xdebug for the webserver, e.g. make XDEBUGW=1 start.

You can now continue with generating code.

Using Docker

You need Docker and Docker Compose installed.

Create the repository:

composer create-project cebe/yii2-app-api my-api

For the easiest way you need GNU make, then run:

make start-docker

This uses docker-compose to start docker containers for the API and the backend including a database.

You can now continue with generating code.

Note: If you don't have GNU make, you need to copy the configuration files as in the PHP directly section, then run:

cp docker-compose.override.dist.yml docker-compose.override.yml
docker-compose up -d
docker-compose exec backend-php sh -c 'cd /app && composer install'

Generate Code

At this point you can start generating your API code to play with it by following the instructions below. If you'd like to start a real project instead of just playing around you can find more detailed documentation in docs/README.md specifically the "Getting Started"-Section.

Console

Tip: If you use Docker, run make cli before running any of these commands.

Run ./yii gii/api to generate your API code. The --openApiPath parameter specifies the path to your OpenAPI spec file. The following example will generate API code for the OpenAPI petstore example.

./yii gii/api --openApiPath=https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.0.2/examples/v3.0/petstore-expanded.yaml

Note: If the OpenAPI spec file is present locally on the file system, then openApiPath must be specified as an absolute path, relative paths will not work correctly. On UNIX based OS it must start with /. Example: /home/user/documents/MyProjectOpenAPISpec.yml

Run ./yii gii/api --help for a list of configuration options. You may also adjust the configuration in config/gii-generators.php.

Then set up the database:

./yii migrate/up
./yii faker

Web

To use the web generator, open http://localhost:8338/gii and select the REST API Generator.

Gii - REST API Generator

Enter the path or URL to the "OpenAPI 3 Spec file", e.g. https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.0.2/examples/v3.0/petstore-expanded.yaml.

Click "Preview":

Gii - REST API Generator - Generated files

Click "Generate" to generate API files.

Then set up the database by running the following commands on the command line:

./yii migrate/up
./yii faker

Try it

cd api
make start

Your API is now available at http://localhost:8337/. Try to access an endpoint of your spec via curl:

$ curl http://localhost:8337/pets
[
    {
        "name": "Eos rerum modi et quaerat voluptatibus.",
        "tag": "Totam in commodi in est nisi nihil aut et."
    },
    {
        "name": "Voluptas quia eos nisi deleniti itaque aspernatur aspernatur.",
        "tag": "Temporibus id culpa dolorem sequi aut."
    },
    {
        "name": "Facere aut similique laboriosam omnis perferendis et.",
        "tag": "Quo harum quo et ea distinctio non quam."
    },
    ...
]

Application structure

This application template consists of 3 application tiers:

  • api, contains the Yii application for the REST API.
  • console, contains the Yii application for console commands, cronjobs or queues (yii command).
  • backend, contains the Yii application for a CRUD backend on the API data.

The following list explains the directory structure in more detail:

  • api/ - API application tier

    • config/ - configuration for API tier
      • url-rules.php - custom URL rules
      • url-rules.rest.php - URL rules generated from OpenAPI Description
      • components.php - application components
      • app.php - Yii application config (+ overrides for different environments app-*.php)
    • controllers/ - Controller classes generated from OpenAPI Description
    • web/ - public web directory for API application
  • backend/ - Backend application tier

    • config/ - configuration for Backend tier
      • components.php - application components
      • app.php - Yii application config (+ overrides for different environments app-*.php)
    • controllers/ - Controller classes
    • views/ - View files
    • web/ - public web directory for Backend application
  • common/ - common code files

    • models/ - model classes generated from OpenAPI Description
    • migrations/ - database migrations generated from OpenAPI Description
  • config/ - Common configuration for all application tiers

    • components.php - Yii application components (+ overrides for different environments components-*.php)
    • env.php - Environment setup (YII_DEBUG, YII_ENV, path aliases, composer autoloader)
    • events.php - Class wide event listeners
    • gii-generators.php - configuration for the Gii code generator (allows to set default values for the ApiGenerator)
    • params.php - Configuration for Yii::$app->params
  • console/ - Console application tier

    • config/ - configuration for Console tier
      • components.php - application components
      • app.php - Yii application config (+ overrides for different environments app-*.php)
  • logs/ - log files

  • runtime/ - temporary runtime files

Development

Below commands are helpful while developing this project:

./yii gii/api --openApiPath=/app/openapi/schema.yaml --generateMigrations=0  --generateControllers=0 --generateUrls=0

./yii gii/api --openApiPath=/app/openapi/schema.yaml --generateMigrations=1  --generateControllers=0 --generateUrls=0 --generateModels=0 --generateModelFaker=0

Support

Need help with your API project?

Professional support, consulting as well as software development services are available:

https://www.cebe.cc/en/contact

Development of this library is sponsored by cebe.:cloud: "Your Professional Deployment Platform".

yii2-app-api's People

Contributors

cebe avatar siggi-k avatar sohelahmed7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-app-api's Issues

./yii gii/api --help does not work for PHP 8.1

PHP 8.1.0 (cli) (built: Nov 28 2021 02:36:02) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.0, Copyright (c) Zend Technologies
18:00:26 ~/myproj 563 (master) $ ./yii gii/api --help
PHP Fatal Error 'yii\base\ErrorException' with message 'During inheritance of IteratorAggregate: Uncaught yii\base\ErrorException: Return type of yii\base\Model::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Model.php:1000
Stack trace:
#0 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Model.php(58): yii\base\ErrorHandler->handleError(8192, 'Return type of ...', '/Users/davidnew...', 1000)
#1 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/BaseYii.php(293): include('/Users/davidnew...')
#2 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2-gii/src/Generator.php(39): yii\BaseYii::autoload('yii\\base\\Model')
#3 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/BaseYii.php(293): include('/Users/davidnew...')
#4 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2-gii/src/generators/model/Generator.php(27): yii\BaseYii::autoload('yii\\gii\\Generat...')
#5 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/BaseYii.php(293): include('/Users/davidnew...')
#6 [internal function]: yii\BaseYii::autoload('yii\\gii\\generat...')
#7 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/di/Container.php(508): ReflectionClass->__construct('yii\\gii\\generat...')
#8 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/di/Container.php(386): yii\di\Container->getDependencies('yii\\gii\\generat...')
#9 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/di/Container.php(171): yii\di\Container->build('yii\\gii\\generat...', Array, Array)
#10 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/BaseYii.php(365): yii\di\Container->get('yii\\gii\\generat...', Array, Array)
#11 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2-gii/src/console/GenerateController.php(74): yii\BaseYii::createObject(Array)
#12 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/BaseObject.php(109): yii\gii\console\GenerateController->init()
#13 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Controller.php(98): yii\base\BaseObject->__construct(Array)
#14 [internal function]: yii\base\Controller->__construct('gii', Object(yii\console\Application), Array)
#15 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/di/Container.php(420): ReflectionClass->newInstanceArgs(Array)
#16 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/di/Container.php(171): yii\di\Container->build('yii\\gii\\console...', Array, Array)
#17 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/BaseYii.php(365): yii\di\Container->get('yii\\gii\\console...', Array, Array)
#18 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Module.php(589): yii\BaseYii::createObject(Array, Array)
#19 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Module->createController('api')
#20 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/console/Application.php(181): yii\base\Module->runAction('gii/api', Array)
#21 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/console/Application.php(148): yii\console\Application->runAction('gii/api', Array)
#22 /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Application.php(392): yii\console\Application->handleRequest(Object(yii\console\Request))
#23 /Users/davidnewcomb/myproj/yii(9): yii\base\Application->run()
#24 {main}'

in /Users/davidnewcomb/myproj/vendor/yiisoft/yii2/base/Model.php:58

Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()

I changed to:

PHP 7.1.33 (cli) (built: Nov 24 2021 20:07:53) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.1.33, Copyright (c) 1999-2018, by Zend Technologies

and it worked!

Improve FakerController to work with relations

Faker Controller should be able to detect relations and set the foreign key values accordingly.

Inside this for loop:

for($i = 0; $i < 10; $i++) {
$model = $faker->generateModel();
if (!$model->save()) {
print_r($model->getErrors());
}
$this->stdout(".");
}

Check for model relations (yii2-openapi could add a list of known relations to the Faker class for this) and add relations to existing models selecting the existing foreign keys.

e.g.

$model->user_id = $faker->randomElement(User::find()->select('id')->column());

The perfect implementation would event sort models by relation dependencies before generating fake data.

Deactivate an entire Model for x-faker

It must be possible to deactivate an entire Model for x-faker in schema.yaml.
But please do not delete the "ModelFaker" itself!

I have written a function ./yii faker/clear in this pullRequest, which uses the dependencies between the models.
#21

So that everything can be deleted, the reverse order must be observed. However, the sequence itself is determined by "ModelFaker".
This means that the "ModelFaker" should continue to exist, but must not generate any data.

Faker related issues

Following the docs as in README.md

Faker command fails

./yii faker

2 errors are caused because

  1. FakerController looks for models in common/models directory instead of common/models/faker
  2. we should also exclude BaseModelFaker.php as shown in screenshot

faker-2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.