T
T
tryste2019-08-03 15:35:42
Yii
tryste, 2019-08-03 15:35:42

How to setup Yii2 restApi routing?

How to correctly set up standard routing to use your methods

'urlManager' => [
                        'enablePrettyUrl' => true,
                        'showScriptName' => false,
                        'rules' => [
                                    [
                                        'class' => 'yii\rest\UrlRule',
                                        'pluralize' => false,
                                        'controller' => ['ApiController'],
                                        'tokens' => [
                                                '{id}' => '<id:\\w+>'
                                        ],
                                        'patterns' => [
                                                'PUT,PATCH api/{id}/update' => 'api/update',
                                                'DELETE {id}/delete' => 'api/delete',
                                                'GET  {id}' => 'api/get',
                                                'POST ' => 'api/create',
                                                'GET,HEAD' => 'api/index',
                                                   ]
                                ],
                        ],
                ],</blockquote>

And controller:
public function actionIndex()
    {
        //  $id = Yii::$app->request->getQueryParam("id"); //
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return "ok";

    }


    public function actionGet()
    {
        // $id = Yii::$app->request->getQueryParam("id"); //
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return "get";
        //  return $this->render('index');
    }

api/ route returns index action, but api/3 route returns 404

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2019-08-03
@trieste

The request is not correct, as I understand it. Judging by your rules , the Request should be like this: . And perhaps that extra slash

'tokens' => [
     '{id}' => '<id:\w+>'
],

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question