memorodmx/cakephp-rest-api

CakePHP 3 插件,用于提供构建 REST API 服务的基礎支持

安装: 14

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 0

分支: 33

类型:cakephp-plugin

v1.2 2020-07-26 21:18 UTC

This package is auto-updated.

Last update: 2024-09-29 02:09:41 UTC


README

Build Status GitHub license Total Downloads Latest Stable Version

此插件为您的 CakePHP 3 应用程序提供构建 REST API 服务的基礎支持。有关如何實現的詳細指南,請參考此處 - CakePHP: 使用 RestApi 插件构建 REST API

要求

此插件有以下要求

  • CakePHP 3.0.0 / 4.0.0 或更高版本。
  • PHP 5.4.16 或更高版本。

安装

您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。

安装 composer 包的推荐方法是

  • 对于 CakePHP 4.0 或更高版本
composer require memorodmx/cakephp-rest-api "^1.2"
  • 对于 CakePHP 3.0 或更高版本
composer require memorodmx/cakephp-rest-api "^1.1"

安装后,加载插件

Plugin::load('RestApi', ['bootstrap' => true]);

或者,您可以使用 shell 命令加载插件

$ bin/cake plugin load -b RestApi

使用方法

您只需要创建与 API 相关的控制器,并将其扩展到 ApiController 而不是默认的 AppController。您只需在 apiResponse 变量中设置您的結果,并在 httpStatusCode 变量中设置您的響應代碼。例如,

namespace App\Controller;

use RestApi\Controller\ApiController;

/**
 * Foo Controller
 */
class FooController extends ApiController
{

    /**
     * bar method
     *
     */
    public function bar()
    {
	// your action logic

	// Set the HTTP status code. By default, it is set to 200
	$this->httpStatusCode = 200;

	// Set the response
        $this->apiResponse['you_response'] = 'your response data';
    }
}

您可以在您的操作函數中根據您的需求定義您的邏輯。對於上面的例子,您將以以下 json 格式獲得以下響應,

{"status":"OK","result":{"you_response":"your response data"}}

上面例子的 URL 將是 http://yourdomain.com/foo/bar。您可以通过在 APP/config/routes.php 中设置路由来自定义它。

簡單 :)

配置

此插件提供與響應格式、CORS、請求日誌和 JWT 驗證相關的多個配置。默認配置如下,並定義在 RestApi/config/api.php 中。

<?php

return [
    'ApiRequest' => [
        'debug' => false,
        'responseType' => 'json',
        'xmlResponseRootNode' => 'response',
    	'responseFormat' => [
            'statusKey' => 'status',
            'statusOkText' => 'OK',
            'statusNokText' => 'NOK',
            'resultKey' => 'result',
            'messageKey' => 'message',
            'defaultMessageText' => 'Empty response!',
            'errorKey' => 'error',
            'defaultErrorText' => 'Unknown request!'
        ],
        'log' => false,
	'logOnlyErrors' => true,
        'logOnlyErrorCodes' => [404, 500],
        'jwtAuth' => [
            'enabled' => true,
            'cypherKey' => 'R1a#2%dY2fX@3g8r5&s4Kf6*sd(5dHs!5gD4s',
            'tokenAlgorithm' => 'HS256'
        ],
        'cors' => [
            'enabled' => true,
            'origin' => '*',
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];

Debug

在開發環境中將 debug 設置為 true 以在響應中獲得原始異常信息。

響應格式

它支持 jsonxml 格式。默認的響應格式是 json。將 responseType 設置為更改您的響應格式。在 xml 格式的情况下,您可以使用 xmlResponseRootNode 參數設置根元素名稱。

使用 JWT 驗證請求身份驗證

您可以在 API 請求中檢查身份驗證令牌的存在。默認是啟用的。您需要定義一個旗標 allowWithoutTokentruefalse。例如,

$routes->connect('/demo/foo', ['controller' => 'Demo', 'action' => 'foo', 'allowWithoutToken' => false]);

上述 API 方法將需要在請求中提供身份驗證令牌。您可以在頭部、GET 參數或 POST 字段中傳送身份驗證令牌。

如果您想在頭部傳送令牌,請使用以下格式。

Authorization: Bearer [token]

在 GET 或 POST 參數的情况下,請在 token 參數中傳送令牌。

生成 jwt 令牌

此插件提供了一個用於生成 jwt 令牌並使用相同的金鑰和算法簽名的工具類。在需要的地方使用 JwtToken::generate() 方法。您最可能需要在用戶登錄和註冊 API 中使用它。參考以下示例,

<?php

namespace App\Controller;

use RestApi\Controller\ApiController;
use RestApi\Utility\JwtToken;

/**
 * Account Controller
 *
 */
class AccountController extends ApiController
{

    /**
     * Login method
     *
     * Returns a token on successful authentication
     *
     * @return void|\Cake\Network\Response
     */
    public function login()
    {
        $this->request->allowMethod('post');

        /**
         * process your data and validate it against database table
         */

	// generate token if valid user
	$payload = ['email' => $user->email, 'name' => $user->name];

        $this->apiResponse['token'] = JwtToken::generateToken($payload);
        $this->apiResponse['message'] = 'Logged in successfully.';
    }
}

cors

默認情況下,cors 請求啟用並允許從所有域來訪問。您可以通过在 APP/config/api.php 中創建配置文件來覆蓋這些設置。文件的內容將如下所示,

<?php
return [
    'ApiRequest' => [
        'cors' => [
            'enabled' => true,
            'origin' => '*',
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];

要禁用 cors 請求,請將 enabled 旗標設置為 false。要允許從特定域發起請求,請在 origin 选项中設置它們,如,

<?php
return [
    'ApiRequest' => [
        'cors' => [
            'enabled' => true,
            'origin' => ['localhost', 'www.example.com', '*.example.com'],
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];

記錄請求和響應

默认情况下,请求日志是禁用的。您可以通过在APP/config/api.php中创建/更新配置文件来覆盖此设置。文件内容如下所示:

<?php
return [
    'ApiRequest' => [
        'log' => true,
        // other config options
    ]
];

启用日志后,您需要在数据库中创建一个表。以下是该表的架构。

CREATE TABLE IF NOT EXISTS `api_requests` (
  `id` char(36) NOT NULL,
  `http_method` varchar(10) NOT NULL,
  `endpoint` varchar(2048) NOT NULL,
  `token` varchar(2048) DEFAULT NULL,
  `ip_address` varchar(50) NOT NULL,
  `request_data` longtext,
  `response_code` int(5) NOT NULL,
  `response_type` varchar(50) DEFAULT 'json',
  `response_data` longtext,
  `exception` longtext,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

或者,您可以使用bake命令自动生成上述表。

$ bin/cake migrations migrate --plugin RestApi

仅记录错误响应

有时,没有必要记录每个请求和响应。我们只想在发生错误时记录请求和响应。为此,您可以使用logOnlyErrors选项设置额外的设置。

'logOnlyErrors' => true, // it will log only errors
'logOnlyErrorCodes' => [404, 500], // Specify the response codes to consider

如果设置了logOnlyErrors,则只会记录不等于200 OK的请求和响应。您可以指定仅记录特定响应代码的请求。您可以在数组格式中指定响应代码,并在logOnlyErrorCodes选项中指定它们。这将仅在log选项设置为true时生效。

響應格式

API的默认响应格式为json,其结构定义如下。

{
  "status": "OK",
  "result": {
    //your result data
  }
}

如果您将httpResponseCode设置为除200以外的任何值,则status值将为NOK,否则为OK。在发生异常的情况下,它将自动处理并设置适当的状态码。

您可以通过在您的APP/config/api.php文件中覆盖它们来修改默认的响应配置,例如OK响应的文本,主要响应数据的键等。

xml格式的情况下,响应结构将如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <status>1</status>
    <result>
        // your data
    </result>
</response>

示例

以下是一些示例,以了解此插件的工作方式。

检索文章

让我们创建一个API,它返回包含基本详情(如id和标题)的文章列表。我们的控制器将如下所示:

<?php

namespace App\Controller;

use RestApi\Controller\ApiController;

/**
 * Articles Controller
 *
 * @property \App\Model\Table\ArticlesTable $Articles
 */
class ArticlesController extends ApiController
{

    /**
     * index method
     *
     */
    public function index()
    {
        $articles = $this->Articles->find('all')
            ->select(['id', 'title'])
            ->toArray();

        $this->apiResponse['articles'] = $articles;
    }
}

上述API调用的响应如下所示:

{
  "status": "OK",
  "result": {
    "articles": [
      {
        "id": 1,
        "title": "Lorem ipsum"
      },
      {
        "id": 2,
        "title": "Donec hendrerit"
      }
    ]
  }
}

异常处理

此插件将处理从您的操作中抛出的异常。例如,如果您的API方法仅允许POST方法,而有人发起一个GET请求,它将生成包含正确HTTP响应代码的NOK响应。例如:

<?php

namespace App\Controller;

use RestApi\Controller\ApiController;

/**
 * Foo Controller
 *
 */
class FooController extends ApiController
{

    /**
     * bar method
     *
     */
    public function restricted()
    {
        $this->request->allowMethod('post');
        // your other logic will be here
        // and finally set your response
        // $this->apiResponse['you_response'] = 'your response data';
    }
}

响应将如下所示:

{"status":"NOK","result":{"message":"Method Not Allowed"}}

抛出异常的另一个示例:

<?php

namespace App\Controller;

use Cake\Network\Exception\NotFoundException;
use RestApi\Controller\ApiController;

/**
 * Foo Controller
 *
 */
class FooController extends ApiController
{

    /**
     * error method
     *
     */
    public function error()
    {
        $throwException = true;

        if ($throwException) {
            throw new NotFoundException();
        }

        // your other logic will be here
        // and finally set your response
        // $this->apiResponse['you_response'] = 'your response data';
    }
}

并且响应将是:

{"status":"NOK","result":{"message":"Not Found"}}

报告问题

如果您对此插件有任何问题或任何错误,请请在GitHub上创建问题。