Home > Mobile >  Yii2: Rest POST Request Parameters not arriving
Yii2: Rest POST Request Parameters not arriving

Time:08-08

Good morning,

I dont get any further in this Topic so i am writing a Question here.

First of all i created a DB Table with Data from the Tutorial: https://www.yiiframework.com/doc/guide/2.0/en/start-databases

Then i created a Rest Controller from that Tutorial with the Data above: https://www.yiiframework.com/doc/guide/2.0/en/rest-quick-start

The first example GET Request from the Tutorial works fine and gives me all of the data from the DB. My Request URL: http://XX.X.X.12:XX90/country/

Now we come to my Error when trying to create a new Country in the DB via a POST Request. When using the CURL Command from underneath the Tutorial with my Test-Data i get following error:

SQLSTATE[HY000]: General error: 1364 Field 'code' doesn't have a default value**strong text**

(
    [0] => HY000
    [1] => 1364
    [2] => Field 'code' doesn't have a default value
)

My standard logging from rest api says that the POST Var is empty, but why? I also tested sending POST Request via a Tool (Postman) but i get the same error.

$_GET = []

$_POST = []

$_FILES = []

$_COOKIE = []

$_SERVER = [....]

My Model:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord
{
}

My Controller:

<?php

namespace app\controllers;

use yii\rest\ActiveController;

class CountryController extends ActiveController
{
    public $modelClass = 'app\models\Country';
}

My CURL Request:

curl -i -H "Accept:application/json" -H "Content-Type:application/json" \
    -XPOST "http://XX.X.X.12:XX90/countries/" \
    -d '{"code": "TEST", "name": "TestCountry", "population": 01}'

My web.php Config:

<?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',
    ],
    'name' => 'Yii2-ExtJS Rest API',
    'modules' => [
        'user' => [
            'class' => Da\User\Module::class,
            // ...other configs from here: [Configuration Options](installation/configuration-options.md), e.g.
            'administrators' => ['admin'], // this is required for accessing administrative actions
            // 'generatePasswords' => true,
            // 'switchIdentitySessionKey' => 'myown_usuario_admin_user_key',
        ],
        'debug' => [
            'class' => 'yii\debug\Module',
            'allowedIPs' => ['XX.X.X.XXX', 'XX.XXX.XXX.XXX', '127.0.0.1', '::1']
        ],
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'XXXXXXXXXXXXXXXX',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ] 
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => \yii\symfonymailer\Mailer::class,
            'viewPath' => '@app/mail',
            // send all mails to a file by default.
            'useFileTransport' => true,
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                  //  'levels' => ['error', 'warning', 'trace', 'info'],
                ],
            ],
        ],
        'db' => $db,
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => false,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule',
                 'controller' => 'country'],
            ], 
        ],
    ],
    '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' => ['XX.X.X.XX', '::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;

Suggestions?

CodePudding user response:

You need to declare validation rules for working with the Rest API

Thanks to @Bizley

My Country Model now:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord
{

    public function rules()
    {
        return [
            [['code', 'name', 'population'], 'required']
        ];
    }
}
  • Related