Setting Routes for RestApi in Yii2

谁说胖子不能爱 提交于 2019-12-13 09:26:09

问题


I am trying to make rest api with my methods.

'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => ['ApiController'],
        'patterns' => [
            'PUT,PATCH api/{id}/update' => 'update',
            'DELETE api/{id}/delete' => 'delete',
            'GET,HEAD api/{id}' => 'get',
            'POST api/{id}/create' => 'create',
            'GET,HEAD' => 'api/index',
            '{id}' => 'options',
            '' => 'options',
        ]
    ],

Api controller:

/**
 * Displays homepage.
 *
 * @return string
 */
public function actionIndex()
{
    //  $id = Yii::$app->request->getQueryParam("id"); //
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return "ok";

}

/**
 * Displays homepage.
 *
 * @return string
 */
public function actionGet($id)
{
    // $id = Yii::$app->request->getQueryParam("id"); //
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return "get";
}

Url api returns index action, but url api/1 doesn't return get action.

How to configure routing?


回答1:


If you are ok with the default actions provided by yii you can simplify your code quite a bit to make it work.

  1. Configure the response type on the application configuration, then you won't need to do it in each method.
  2. Remove the 'patterns' element from your rules, yii automatically matches the patterns that you are trying to use.
  3. Decide if you want to pluralize your rules or not, if you don't want to pluralize them you need to add 'pluralize' => false to your configuration rules.

web.config

// configure json response globally
'response' => [
    'format' => Response::FORMAT_JSON,
    'formatters' => [
        Response::FORMAT_JSON => [
            'class' => '\yii\web\JsonResponseFormatter',
            'prettyPrint' => YII_DEBUG,
            'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
        ]
    ],
],

// Add ApiController rules
'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'api',
        // uncoment the next line if you want to request '/api/2' instead of '/apis/2'
        // 'pluralize' => false
    ],
    // ... more rules here
]

ApiController

<?php
namespace app\controllers;

use yii\rest\Controller;

class ApiController extends Controller
{

    public function actionIndex()
    {
        return 'Api index action';
    }

    public function actionView($id)
    {
        return "Get item $id";
    }
}

Using the configuration provided you can request the index route sending a GET request to the /apis endpoint, to control the result customize actionIndex, you can provide a dataProvider as the response and the formatter element will deal with it correctly.

To request one element of the collection, send a GET request to the /apis/5 endpoint, where 5 is just an example $id, if you return a model, the formatter will deal with it using the fields attribute of the model.

If you want to use endpoints like in your question, i.e. without the plural form, uncomment the pluralize line on the example, the endpoints will be /api and /api/5.

There are multiple examples of this on the official documentation, the quick start and building a REST API pages make for some good reading and are packed with examples.

Personally I would recommend not naming a controller ApiController, it seems confusing, your API probably has api already on the url so you will end up with urls like https://api.mydomain.com/api/5



来源:https://stackoverflow.com/questions/57337958/setting-routes-for-restapi-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!