Shahid Thaika
Shahid Thaika

Reputation: 2305

Unable to get POST working with Yii2 RESTful API

I coded a RESTful API in Yii2-Basic using ActiveController and Basic Authentication. I can get the GET method to work, but when I try the Post, using Postman Chrome Extension, it throws an error saying "Method Not Allowed. This url can only handle the following request methods: GET, HEAD.".

Do I need to configure anything on my web server to test this, or require additional functions in the controller? I even tried this with a really simple table with two columns and also set the columns as safe, as hinted in another question.

Appreciate any help in this regard. Below is my current code:

<?php
namespace app\controllers;

use yii\rest\ActiveController;
use yii\filters\auth\HttpBasicAuth;

class TestController extends ActiveController
{
    public $modelClass = 'app\models\Test';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
        ];
        return $behaviors;
    }
}

The URL I am using to test is: http://localhost/test

Upvotes: 1

Views: 1967

Answers (4)

hilton123456
hilton123456

Reputation: 1

I add prefix in urlManager as below:

...
,
[
    'class'      => 'api\modules\web\controllers\rest\UrlRule',
    'controller' => [
        'web/device'
    ],
    'prefix'=>'v1',
    'pluralize'  => false,
],
...
    
   

and POST working well. url like:[POST] http://localhost/v1/device/entry

Upvotes: 0

Vijay Maurya
Vijay Maurya

Reputation: 109

try this : $params = \Yii::$app->request->post();

for reference: https://forum.yiiframework.com/t/rest-api-model-create-problem/83651

Upvotes: 0

Shahid Thaika
Shahid Thaika

Reputation: 2305

Turns out I was using the wrong end point. Using this end point worked for me:

http://localhost/test/create

Upvotes: 1

gmc
gmc

Reputation: 3990

Try to splicitly allow the POST method for your action:

$behaviors['verbs'] = [
                'class' => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'index' => ['post'],
                ],
            ]; 

Upvotes: 1

Related Questions