Yii2 RESTful API 学习笔记第一节:基础配置与接口

一、配置文件main.php

// 已删除未修改的配置
[
    'id' => 'app-api',
    'controllerNamespace' => 'api\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-api',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',  // 可接收 JSON 格式提交的数据
            ],
        ],
        'user' => [
            'identityClass' => 'api\models\User',
            'enableAutoLogin' => true,
            'enableSession' => false,
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,  // 路由友好化
            'enableStrictParsing' => true,  // 启用严格解析
            'showScriptName' => false,  // 是否显示单入口
            'rules' => [                // 路由规则
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'article',
                ],
            ],
        ],
    ],
];

二、小程序相关代码之wxml

  <view bindtap='bindReadTap'>读取列表数据</view>
  <view bindtap='bindReadOneTap'>读取一条数据</view>
  <view bindtap='bindCreateTap'>新增数据</view>
  <view bindtap='bindUpdateTap'>修改数据</view>
  <view bindtap='bindDeleteTap'>删除数据</view>
  <view bindtap='bindOtherTap'>其他http动词</view>

三、小程序相关代码之js

//读取列表数据
bindReadTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'GET',
//    data: {page: 2},  // 页码
    success: function (res) {
      console.log(res.data);
    }
  })
},

//读取一条数据
bindReadOneTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles/5',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'GET',
    success: function (res) {
      console.log(res.data);
    }
  })
},

//新增数据
bindCreateTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'POST',
    data: {
      title: "API 添加文章接口",
      content: "通过API接口添加一篇文章"
    },
    success: function (res) {
      console.log(res.data)
    }
  })
},

//修改数据
bindUpdateTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles/36',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'PUT',
    data: {
      title: "API 修改文章接口",
      content: "通过API接口修改一篇文章",
    },
    success: function (res) {
      console.log(res.data)
    }
  })
},

//删除数据
bindDeleteTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles/34',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'DELETE',
    success: function (res) {
      console.log(res.data)
    }
  })
},

//其他http动词
bindOtherTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles/35',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'OPTIONS',
    //method: 'HEAD',
    success: function (res) {
      console.log(res.data)
    }
  })
},

四:控制器相关代码ArticleController.php

namespace api\controllers;

use Yii;
use yii\rest\ActiveController;
use api\models\Article;

class ArticleController extends ActiveController
{
    public $modelClass = 'api\models\Article';

    // 因个人数据库原因, 需要重写添加和删除操作
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['create']);
        unset($actions['delete']);
        return $actions;
    }

    public function actionCreate()
    {
        $model = new Article();
        $model->loadDefaultValues();
        $model->load(Yii::$app->request->post(), '');
        $model->save();
        return $model;
    }

    public function actionDelete($id)
    {
        $model = Article::findOne($id);
        return $model->delete(true);
    }
}