jacreditoh/cakephp-rest-api

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

安装: 550

依赖: 0

建议者: 0

安全: 0

星星: 1

观察者: 1

分支: 0

公开问题: 0

类型:cakephp-plugin

v1.0 2019-12-12 09:15 UTC

This package is not auto-updated.

Last update: 2024-09-28 07:44:31 UTC


README

我们使用我们的 Packagist 仓库: https://packagist.org.cn/packages/jacreditoh/cakephp-rest-api

此插件为您的 CakePHP 3 应用程序提供构建 REST API 服务的基本支持。在此处阅读如何实现的详细指南 - CakePHP: 使用 RestApi 插件构建 REST API

要求

此插件有以下要求

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

安装

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

安装 composer 包的推荐方式是

composer require multidots/cakephp-rest-api

安装后,加载插件

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';
    }
}

您可以在操作函数中根据您的需要定义您的逻辑。对于上述示例,您将获得以下格式的响应

{"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 设置为 true 以在响应中获取原始异常消息。

响应格式

它支持 jsonxml 格式。默认响应格式是 json。将 responseType 设置为更改您的响应格式。在 xml 格式的情况下,您可以使用 xmlResponseRootNode 参数设置根元素名称。

使用 JWT 进行请求认证

您可以在 API 请求中检查是否存在 auth 令牌。默认情况下,它是启用的。您需要将 allowWithoutToken 标志定义为 truefalse。例如,

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

上述 API 方法将要求请求中存在 auth 令牌。您可以通过头部、GET 参数或 POST 字段传递 auth 令牌。

如果您想在头部传递令牌,请使用以下格式。

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 上创建一个问题。