Yii Framework Forum

Help please to start simple API REST


(Ruslan) #1

Good day to all. help me please.
The simplest task is required: to receive events with JSON data via REST from VK.com / Store them in the database. Further processing is a separate issue.

I installed the framework, added the BASIC application.
The application works at the address [url] https: // url_site / basic / web [/ url]

Added a table and generated a model for it through gii
\basic\models\Participants.php
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "participants".
 *
 * @property int $id
 * @property int $id_participants Идентификатор в ВК
 * @property string $first_name Имя
 * @property string $last_name Фамилия
 * @property string $bdate День рождения
 */
class Participants extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'participants';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id_participants', 'first_name', 'last_name', 'bdate'. 'reg_date'], 'required'],
            [['id_participants'], 'integer'],
            [['first_name', 'last_name'], 'string'],
            [['bdate'], 'safe'],
            [['reg_date'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'id_participants' => 'Идентификатор в ВК',
            'first_name' => 'Имя',
            'last_name' => 'Фамилия',
            'bdate' => 'День рождения',
            'reg_date' => 'Дата и время когда добавился в группу',
        ];
    }
}

Then I went through the description https://www.yiiframework.com/doc/guide/2.0/ru/rest-quick-start Quick start creating RESTfulAPI [/ url]

Created a controller
\basic\controllers\CallBackController.php

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\controllers;

use yii\rest\ActiveController;

class CallBackController extends ActiveController
{
    public $modelClass = 'app\models\Participants';
    //public $modelClass = 'basic\models\Participants';
}

On next step create php file for VK callback
\basic\web\callback.php

<?php

// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
    die('You are not allowed to access this file.');
}

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

$config = require __DIR__ . '/../config/rest.php';

(new yii\web\Application($config))->run();

well, for it I created a configuration file by copying web.php and adding to it according to the instructions

\basic\config\rest.php

<?php

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';

$config = [
    'id' => 'rest',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'rest',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ],

        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'callback'],
            ],
        ], 
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        'allowedIPs' => ['127.0.0.1', '::1' , 'my_ip', 'ip_ssl_route'],
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        'allowedIPs' => ['127.0.0.1', '::1',  'my_ip', 'ip_ssl_route'],
    ];
}

return $config;

as a result, I can’t get anything to get from REST

view-source:https://url_site/basic/callback/callback/1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /basic/callback/callback/1 was not found on this server.</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at url_site Port 80</address>
</body></html>

view-source:https://url_site/basic/callback/1
view-source:https://url_site/basic/web/callback/1
view-source:https://url_site/callback/1

same answers

What am I doing wrong?
Help please.


(Schanz15) #2

Until that point, everything looked alright. You do not need to create any other files inside the basic/web directory. Every request is handled by index.php and routing is done by Yii.

As a matter of fact it should be enough to call https://url_site/basic/web/index.php?r=callback . If you want to have pretty URL’s you need to enable them in config/web.php and also configure your webserver to properly handle those requests (please have a look at the guide for further information). In that case, you should also consider to make basic/web your web root directory so that users are not allowed to access any other files through their browser (e.g. https://url_site/basic/runtime/logs/app.log)


(Ruslan) #3

Thank you for responding.
I understood and deleted the file \basic\web\callback.php
Changed root folder host settings to \var\www\basic\web\

For the test, removed from the settings urlManager

Now /basic/config/web.php

<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '12345',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ],
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,
/*        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => false,
            'showScriptName' => false,
            'rules' => [
                //['class' => 'yii\web\UrlRule', 'controller' => 'site'], 
                ['class' => 'yii\rest\UrlRule', 'controller' => 'callback'],
            ],
 
        ], */
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        'allowedIPs' => ['127.0.0.1', '::1'],
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        'allowedIPs' => ['127.0.0.1', '::1',],
    ];
}

return $config;

At that moment
https://site_url/index.php working
https://site_url/index.php?r=site%2Flogin working
https://site_url/index.php?r=callback not working
https://site_url/index.php?r=callback%2Fget not working

/basic/runtime/logs/app.log

2019-02-15 20:37:11 [some_ip][-][qweqweqweqweqwe][error][yii\web\HttpException:404] exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "callback".' in /var/www/basic/vendor/yiisoft/yii2/base/Module.php:537
Stack trace:
#0 /var/www/basic/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('callback', Array)
#1 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /var/www/basic/web/index.php(15): yii\base\Application->run()
#3 {main}

Next exception 'yii\web\NotFoundHttpException' with message 'Page not found.' in /var/www/basic/vendor/yiisoft/yii2/web/Application.php:115
Stack trace:
#0 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /var/www/basic/web/index.php(15): yii\base\Application->run()
#2 {main}
2019-02-15 20:37:11 [some_ip][-][qweqweqweqweqwe][info][application] $_GET = [
    'r' => 'callback'
]

$_POST = []

$_FILES = []

$_COOKIE = [12312312323123213123
]

$_SESSION = [
    '__flash' => []
    '__captcha/site/captcha' => 'huvubel'
    '__captcha/site/captchacount' => 1
]

$_SERVER = [
    'HTTP_HOST' => 'site_url'
    'HTTP_CONNECTION' => 'Keep-Alive'
    'HTTP_ACCEPT_ENCODING' => 'gzip'
    'HTTP_CF_IPCOUNTRY' => 'RU'
    'HTTP_X_FORWARDED_FOR' => 'some_ip'
    'HTTP_CF_RAY' => '4a9a922c8d186349-FRA'
    'HTTP_X_FORWARDED_PROTO' => 'https'
    'HTTP_CF_VISITOR' => '{\"scheme\":\"https\"}'
    'HTTP_CACHE_CONTROL' => 'max-age=0'
    'HTTP_UPGRADE_INSECURE_REQUESTS' => '1'
    'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
    'HTTP_ACCEPT_LANGUAGE' => 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'
    'HTTP_COOKIE' => '13123131232131232131'
    'HTTP_CF_CONNECTING_IP' => 'some_ip'
    'HTTP_CDN_LOOP' => 'cloudflare'
    'PATH' => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
    'SERVER_SIGNATURE' => '<address>Apache/2.4.18 (Ubuntu) Server at site_url Port 80</address>
'
    'SERVER_SOFTWARE' => 'Apache/2.4.18 (Ubuntu)'
    'SERVER_NAME' => 'site_url'
    'SERVER_ADDR' => 'some_ip'
    'SERVER_PORT' => '80'
    'REMOTE_ADDR' => 'some_ip'
    'DOCUMENT_ROOT' => '/var/a/site_url/basic/web'
    'REQUEST_SCHEME' => 'http'
    'CONTEXT_PREFIX' => ''
    'CONTEXT_DOCUMENT_ROOT' => '/var/a/site_url/basic/web'
    'SERVER_ADMIN' => '[no address given]'
    'SCRIPT_FILENAME' => '/var/a/site_url/basic/web/index.php'
    'REMOTE_PORT' => '32226'
    'GATEWAY_INTERFACE' => 'CGI/1.1'
    'SERVER_PROTOCOL' => 'HTTP/1.1'
    'REQUEST_METHOD' => 'GET'
    'QUERY_STRING' => 'r=callback'
    'REQUEST_URI' => '/index.php?r=callback'
    'SCRIPT_NAME' => '/index.php'
    'PHP_SELF' => '/index.php'
    'REQUEST_TIME_FLOAT' => 1550263031.79
    'REQUEST_TIME' => 1550263031
]

(Ruslan) #4

Forgot to say, in the browser i see:

Not Found (#404)

Page not found.

The above error occurred while the Web server was processing your request.

Please contact us if you think this is a server error. Thank you.


(Schanz15) #5

Ah yes, I missed that the Controller is named in CamelCase (CallBack) which translates to ?r=call-back as route parameter.