Skip to content
Advertisement

Yii2: Rest POST Request Parameters not arriving

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 appmodels;

use yiidbActiveRecord;

class Country extends ActiveRecord
{
}

My Controller:

<?php

namespace appcontrollers;

use yiirestActiveController;

class CountryController extends ActiveController
{
    public $modelClass = 'appmodelsCountry';
}

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' => DaUserModule::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' => 'yiidebugModule',
            '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' => 'yiiwebJsonParser',
            ] 
        ],
        'cache' => [
            'class' => 'yiicachingFileCache',
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => yiisymfonymailerMailer::class,
            'viewPath' => '@app/mail',
            // send all mails to a file by default.
            'useFileTransport' => true,
        ],
        'authManager' => [
            'class' => 'yiirbacDbManager',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yiilogFileTarget',
                  //  'levels' => ['error', 'warning', 'trace', 'info'],
                ],
            ],
        ],
        'db' => $db,
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => false,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yiirestUrlRule',
                 'controller' => 'country'],
            ], 
        ],
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yiidebugModule',
        // 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' => 'yiigiiModule',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
}

return $config;

Suggestions?

Advertisement

Answer

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

Thanks to @Bizley

My Country Model now:

<?php

namespace appmodels;

use yiidbActiveRecord;

class Country extends ActiveRecord
{

    public function rules()
    {
        return [
            [['code', 'name', 'population'], 'required']
        ];
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement