Yii2: Rest POST Request Parameters not arriving - php

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?

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

Api/v1 does not exist in config when running php artisan serve

I would like to build an API that does a GET request to a third party API. I created a controller that houses this logic and registered this as an HTTP end point using the JsonApiRoute::server() facade. I am absolutely new to Laravel and PHP.
However when I run php artisan serve I get the error:
Server /api/v1 does not exist in config or is not a valid class.
This is my code in routes:
JsonApiRoute::server('/api/v1')
->prefix('/api/v1')
->resources(function ($server) {
$server->resource('retrieve');
});
This is the code I have in config-> json-api-default:
return [
'resolver' => \CloudCreativity\LaravelJsonApi\Resolver\ResolverFactory::class,
'namespace' => null,
'by-resource' => true,
'model-namespace' => null,
'resources' => [
'posts' => \App\Post::class,
],
'use-eloquent' => true,
'url' => [
'host' => null,
'namespace' => '/api/v1',
'name' => 'api:v1:',
],
'controllers' => [
'transactions' => true,
'connection' => null,
],
'jobs' => [
'resource' => 'queue-jobs',
'model' => \CloudCreativity\LaravelJsonApi\Queue\ClientJob::class,
],
'encoding' => [
'application/vnd.api+json',
],
'decoding' => [
'application/vnd.api+json',
],
'providers' => [],
];
and in my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class retrieve extends Controller
{
//
public function retrieveData(Request $request){
$response = Http::withHeaders([
'api-key' => '***',
])->get('https://data.mongodb-api.com/app/data-pkrpq/endpoint/getRandom');
return response()->json(['status'=> true,'data'=> json_decode($response->body()), 'Message'=>'Successfully retrieved'], 200);
}
}

Yii Console Script, Login to User [duplicate]

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Twig not working in Yii2

I want to use Twig in Yii2 framework but it isn't working.
I am using yii2-app-advanced as the base project but I am new in the Yii world so I think I am not configuring Twig in the right way.
First I downloaded it using:
composer require yiisoft/yii2-twig
Then I follow this instructions but it's not easy to understand:
https://github.com/yiisoft/yii2-twig/blob/HEAD/docs/guide/installation.md#configuring-application
It says:
In order to start using Twig you need to configure view component like the following:
[
'components' => [
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => [
'html' => ['class' => '\yii\helpers\Html'],
],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
]
In which file I have to paste this code?
In my index.php file I added the following code but it is not working:
{% if true %}
<p>It is true.</p>
{% else %}
<p>It is false.</p>
{% endif %}
I solved it doing this:
I modified the file backend/config/main-local-php:
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'CPeTotdTU98geIyM7q0PljmCpJbupPN4',
],
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => [
'html' => ['class' => '\yii\helpers\Html'],
],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
The SiteController.php file has the actionIndex() function. I added the extension .twig:
public function actionIndex()
{
return $this->render('index.twig');
}
And then I modified the name of the file backend/views/sire/index.php to index.twig.

Yii2 controller or configuration raise that only handle the following request methods: GET, HEAD

I am trying to do something very simple a REST response using json format.
I created a simple model:
Model
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class Post extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'posts';
}
public function rules()
{
return [
[['title', 'content'], 'required'],
];
}
}
And a simple controller:
Controller
namespace app\controllers;
use Yii;
use yii\rest\ActiveController;
class PostsController extends ActiveController
{
public $modelClass = "app\models\Post";
}
?>
It is the configuration of my web.php file:
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
'cookieValidationKey' => 'wcHYBrv4bXfLJYnWzrpJz_5vARaAeE9U',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
//'showScriptName' => false,
'rules' => [
'class' => 'yii\rest\UrlRule',
'controller' => 'posts',
]
],
Other attributes...
The most important part (I think so) is the urlManager configuration, maybe I am missing something but I don't know where is the error below.
The error
When I execute a request with method GET, everything is Ok, but with any other method it fail. It is the error:
{
"name": "Method Not Allowed",
"message": "Method Not Allowed. This url can only handle the following request methods: GET, HEAD.",
"code": 0,
"status": 405,
"type": "yii\web\MethodNotAllowedHttpException"
}
I want to get a simple response like this guy got in this video I just did the same configuration, step by step.
Thank you.
UPDATE
There is more information, when I using Postman, I got this Headers result.
I don't understand why only ALLOW -> GET, HEAD
It is the Body result:
Try this configuration:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'post'],
],
],
See config and full list of available requests in official docs.
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'author',
'pluralize' => false
],
],
],
When I have to do something like that, I have it a little different. Try to change class in urlManager to "yii\rest\UrlRule"
Exemple (this code works for me ) :
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => [
'post']
]
],
]
Now try to acces to this url POST frontend.dev/basic/web/post whit Postman
namespace app\controllers;
use Yii;
use yii\rest\ActiveController;
class PostsController extends ActiveController
{
public $modelClass = "app\models\Post";
//uncomment actions allowed
public function actions()
{
$actions = parent::actions();
// unset($actions['create']);
// unset($actions['update']);
// unset($actions['delete']);
// unset($actions['view']);
// unset($actions['index']);
return $actions;
}
//setup verb allowed
protected function verbs()
{
return [
'create' => ['POST'],
'update' => ['PUT', 'PATCH', 'POST'],
'delete' => ['DELETE'],
'view' => ['GET'],
'index' => ['GET'],
];
}
}
or setup in config file
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['post', 'user', 'etc', 'etc2'],
'pluralize' => false,
'extraPatterns' => [
'POST' => 'create', // 'xx' refers to 'actionXx'
'PUT {id}' => 'update',
'PATCH {id}' => 'update',
'DELETE {id}' => 'delete',
'GET {id}' => 'view',
'GET {count}' => 'index',
],
],
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],

Yii2 - Getting unknown property: yii\console\Application::user

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Categories