multidots/cakephp-rest-api

此包已被 弃用 并不再维护。作者建议使用 sprintcube/cakephp-rest 包。

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

安装数: 25,094

依赖: 1

推荐者: 0

安全: 0

星标: 71

关注者: 14

分支: 39

开放问题: 22

类型:cakephp-plugin

v1.1.2 2018-07-30 10:08 UTC

This package is not auto-updated.

Last update: 2020-05-14 13:11:20 UTC


README

Build Status GitHub license Total Downloads Latest Stable Version

此插件为您的 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';
    }
}

您可以在您的操作函数中根据您的需求定义逻辑。对于上面的例子,您将得到以下格式的响应(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 设置为 true 以在响应中获取原始异常消息。

响应格式

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

使用 JWT 进行请求身份验证

您可以在 API 请求中检查是否存在身份验证令牌。默认情况下已启用。您需要定义一个 allowWithoutToken 标志并将其设置为 truefalse。例如,

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

上面的 API 方法将要求请求中存在身份验证令牌。您可以通过 header、GET 参数或 POST 字段传递身份验证令牌。

如果您想通过 header 传递令牌,请使用以下格式。

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上提交问题。