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

Overview

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 can now continue with generating code.

Using Docker

You need Docker and Docker Compose installed. For the easiest way you need GNU make, then run:

make docker-up

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:

docker-compose up -d
docker-compose exec backend-php sh -c 'cd /app && composer install'

Generate Code

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

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

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. ☁️ "Your Professional Deployment Platform".

Comments
  • Faker related issues

    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

    bug 
    opened by SOHELAHMED7 1
  • ./yii gii/api --help does not work for PHP 8.1

    ./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!

    bug php 8 
    opened by davidnewcomb 1
  • Improve FakerController to work with relations

    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:

    https://github.com/cebe/yii2-app-api/blob/f3facab5d0978a30f77535913a442547a4ab42e7/console/commands/FakerController.php#L26-L32

    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.

    enhancement help wanted good first issue hacktoberfest 
    opened by cebe 2
  • Submit to swagger-codegen

    Submit to swagger-codegen

    https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources

    Then it will be available in https://editor.swagger.io/# Generate Server dropdown

    help wanted 
    opened by cebe 1
  • JSON-Schema validation

    JSON-Schema validation

    • https://philsturgeon.uk/api/2018/03/30/openapi-and-json-schema-divergence/
    • https://philsturgeon.uk/api/2018/04/13/openapi-and-json-schema-divergence-solved/
    enhancement 
    opened by cebe 0
Releases(2.1.0)
Owner
Carsten Brandt
PGP: 1DEEEED0
Carsten Brandt
BEdita, ready to use back-end API, extensible API-first Content Management

BEdita, a back-end API BEdita 4 is a ready to use back-end API to handle the data of your mobile, IoT, web and desktop applications. It's also an exte

BEdita 65 Oct 31, 2022
A sample CakePHP api application using CakeDC/cakephp-api and swoole as server

CakePHP Application Skeleton composer create-project --prefer-dist cakephp/app Added sample data using https://github.com/annexare/Countries Created m

Marcelo Rocha 3 Jul 28, 2022
Simple live support server with PHP Swoole Websocket and Telegram API

Telgraf Simple live support server with PHP Swoole Websocket and Telegram API. Usage Server Setup Clone repository with following command. git clone h

Adem Ali Durmuş 6 Dec 30, 2022
基于 mirai-api-http 的 PHP 机器人框架

miraiez 开始使用 请在 mirai-api-http 的配置文件中启用 http 和 webhook 适配器 并将 webhook 适配器的回调地址设置为 webhook.php 的所在地址 例如 http://localhost/webhook.php 完成上述步骤后,请修改 config

null 20 Jan 9, 2023
⚡ Micro API using Phalcon Framework

Micro App (Rest API) ⚡ Micro API using Phalcon PHP Framework. PHPDocs I. Requirements A Laptop ?? Docker (docker-compose*) Makefile (cli) II. Installa

Neutrapp 7 Aug 6, 2021
🍃Termwind allows you to build unique and beautiful PHP command-line applications, using the Tailwind CSS API

Termwind allows you to build unique and beautiful PHP command-line applications, using the Tailwind CSS API. In short, it's like Tailwind CSS, but for the PHP command-line applications.

Nuno Maduro 1.8k Jan 3, 2023
PHP REST API using CodeIgniter 3 framework and CRUD operations

PHP REST API using CodeIgniter 3 framework and CRUD operations ?? Hi there, this is a simple REST API built using the Codeigniter 3 framework. And thi

Hanoak 0 Oct 20, 2021
Laravel 8 Project Restrict User Access From IP Addresses. prevent other ip address that want to access over secure api or urls.

block-ip-address-laravel Laravel 8 Project Restrict User Access From IP Addresses. prevent other ip address that want to access over secure api or url

Hasmukh Dharajiya 2 Mar 24, 2022
SIMPLE DONATIONS SITE TO TEST DARAJA 2.0(MPESA) API

SIMPLE DONATIONS SITE TO TEST DARAJA 2.0(MPESA) API MPESA FILES donation.php requires pay.php which has the two functions: customerMpesaSTKPush($phone

Emmanuel Bongwe 2 Jul 16, 2022
Volistx Framework For RESTful API Based on Laravel/Lumen 9.x

Volistx Framework Volistx Framework For RESTful API Based on Laravel/Lumen 9.x This is a framework skeleton for Volistx API platform using Lumen PHP F

Volistx Solutions 2 Nov 18, 2022
An extension to the SLIM framework to implement json API's with great ease.

slim-jsonAPI This is an extension to the SLIM framework to implement json API's with great ease. Installation Using composer you can add use this as y

Jonathan Tavares 269 Jul 23, 2022
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
OpenAPI(v3) Validators for Symfony http-foundation, using `league/openapi-psr7-validator` and `symfony/psr-http-message-bridge`.

openapi-http-foundation-validator OpenAPI(v3) Validators for Symfony http-foundation, using league/openapi-psr7-validator and symfony/psr-http-message

n1215 2 Nov 19, 2021
Generates OpenApi specification for Laravel, Lumen or Dingo using a configuration array and cebe/php-openapi

OpenApi Generator for Laravel, Lumen and Dingo. About The openapi-gen package provides a convenient way to create OpenApi specifications for Laravel,

Jean Dormehl 5 Jan 25, 2022
Ariama Victor (A.K.A. OVAC4U) 106 Dec 25, 2022
A spec compliant, secure by default PHP OAuth 2.0 Server

PHP OAuth 2.0 Server league/oauth2-server is a standards compliant implementation of an OAuth 2.0 authorization server written in PHP which makes work

The League of Extraordinary Packages 6.2k Jan 4, 2023
A Composer script to run a 'test' or 'spec' Composer script against multiple PHP versions.

composer-multitest composer-multitest is a Composer script that runs a test or spec Composer script against multiple PHP versions managed by PHPBrew o

Raphael Stolt 5 Aug 27, 2019
This library provides HTML5 element definitions for HTML Purifier, compliant with the WHATWG spec

HTML5 Definitions for HTML Purifier This library provides HTML5 element definitions for HTML Purifier, compliant with the WHATWG spec. It is the most

Mateusz Turcza 92 Nov 16, 2022
this is a project done with laravel, I created API.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

NIKA ZEREKIDZE 1 Oct 27, 2021
A simple API documentation package for Laravel using OpenAPI and Redoc

Laravel Redoc Easily publish your API documentation using your OpenAPI document in your Laravel Application. Installation You can install this package

Steve McDougall 15 Dec 27, 2022