Jackhad
Jackhad

Reputation: 411

Yii2 Rest API PUT method call is not working

In my controller:

namespace app\api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\filters\VerbFilter;
use yii\web\Response;

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

public function behaviors()
{
    return [
        [
           'class' => 'yii\filters\ContentNegotiator',
           'only' => ['index', 'view','create','update','search'],
           'formats' => ['application/json' =>Response::FORMAT_JSON,],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index'=>['get'],
                'view'=>['get'],
                'create'=>['post'],
                'update'=>['PUT'],
                'delete' => ['delete'],
                'deleteall'=>['post'],
                'search'   => ['get']
            ],

        ]
    ];
}
}`

I try from my POSTMAN App

For create I use POST http://localhost/myapp/api/v1/countries Works fine.But For Update I use PUT http://localhost/myapp/api/v1/countries/16 it returns 16 the record as JSON output not updating as expected.

What was wrong? Thanks!!

Upvotes: 10

Views: 2940

Answers (2)

Pablorotten
Pablorotten

Reputation: 103

In POSTMAN App, open the Request body tab and select x-www-form-urlencoded instead of form-data. That worked for me.

x-www-form-urlencoded selected

Upvotes: 8

Mike Ross
Mike Ross

Reputation: 2972

Here is another option if you feel comfortable using it. Instead of behaviors() you can add something like this and it will serve the same purpose and you wont have any problem.

public function actions()
{
    $actions = parent::actions();
    unset($actions['index']);
    unset($actions['create']);
    unset($actions['delete']);
    unset($actions['update']);
    unset($actions['view']);
    return $actions;
}

Upvotes: -1

Related Questions