All Projects → multidots → Public Cakephp Rest Api

multidots / Public Cakephp Rest Api

Licence: mit
CakePHP 3 plugin for building REST API services

Projects that are alternatives of or similar to Public Cakephp Rest Api

Apiproject
[https://www.sofineday.com], golang项目开发脚手架,集成最佳实践(gin+gorm+go-redis+mongo+cors+jwt+json日志库zap(支持日志收集到kafka或mongo)+消息队列kafka+微信支付宝支付gopay+api加密+api反向代理+go modules依赖管理+headless爬虫chromedp+makefile+二进制压缩+livereload热加载)
Stars: ✭ 124 (+74.65%)
Mutual labels:  cors, jwt
Laravel Api Boilerplate Jwt
A Laravel 5.8 API Boilerplate to create a ready-to-use REST API in seconds.
Stars: ✭ 1,155 (+1526.76%)
Mutual labels:  cors, jwt
Cakephp Jwt Auth
A CakePHP plugin for authenticating using JSON Web Tokens
Stars: ✭ 153 (+115.49%)
Mutual labels:  cakephp, jwt
Typescript Restful Starter
Node.js + ExpressJS + Joi + Typeorm + Typescript + JWT + ES2015 + Clustering + Tslint + Mocha + Chai
Stars: ✭ 97 (+36.62%)
Mutual labels:  cors, jwt
Rust Webapp Starter
Rust single page webapp written in actix-web with vuejs.
Stars: ✭ 151 (+112.68%)
Mutual labels:  cors, jwt
Blog.core
💖 ASP.NET Core 6.0 全家桶教程,前后端分离后端接口,vue教程姊妹篇,官方文档:
Stars: ✭ 3,542 (+4888.73%)
Mutual labels:  cors, jwt
Node Typescript Koa Rest
REST API boilerplate using NodeJS and KOA2, typescript. Logging and JWT as middlewares. TypeORM with class-validator, SQL CRUD. Docker included. Swagger docs, actions CI and valuable README
Stars: ✭ 739 (+940.85%)
Mutual labels:  cors, jwt
Ldap Jwt
Lightweight node.js based web service that provides user authentication against LDAP server (Active Directory / Windows network) credentials and returns a JSON Web Token.
Stars: ✭ 58 (-18.31%)
Mutual labels:  jwt
Grpc Auth Example
Examples of client authentication with gRPC
Stars: ✭ 65 (-8.45%)
Mutual labels:  jwt
Google Auth Library Nodejs
🔑 Google Auth Library for Node.js
Stars: ✭ 1,094 (+1440.85%)
Mutual labels:  jwt
App
Reusable framework for micro services & command line tools
Stars: ✭ 66 (-7.04%)
Mutual labels:  jwt
Duckygo
一个同时支持Session以及JWT的高性能高可用 Golang Restful API 脚手架 !
Stars: ✭ 57 (-19.72%)
Mutual labels:  jwt
Eshop Soa
EShop基于Dubbo实现SOA服务化拆分,并基于RocketMQ解决了分布式事务(新版SpringBootSOASkeleton)
Stars: ✭ 65 (-8.45%)
Mutual labels:  jwt
Aclmanager
Plugin to manage Acl for CakePHP 2.x
Stars: ✭ 59 (-16.9%)
Mutual labels:  cakephp
Train Ai With Django Swagger Jwt
Train AI (Keras + Tensorflow) to defend apps with Django REST Framework + Celery + Swagger + JWT - deploys to Kubernetes and OpenShift Container Platform
Stars: ✭ 66 (-7.04%)
Mutual labels:  jwt
Auth0 Socketio Jwt
Authenticate socket.io incoming connections with JWTs
Stars: ✭ 1,093 (+1439.44%)
Mutual labels:  jwt
Spring React Boilerplate
Boilerplate application to demonstrate how to wire up Spring, JWT Authentication, React, Redux and Websockets
Stars: ✭ 70 (-1.41%)
Mutual labels:  jwt
Jwt Boot Auth
secure spring-boot APIs with JWT
Stars: ✭ 57 (-19.72%)
Mutual labels:  jwt
Flask Restful Authentication
An example for RESTful authentication using nginx, uWSGI, Flask, MongoDB and JSON Web Token(JWT).
Stars: ✭ 63 (-11.27%)
Mutual labels:  jwt
Audit Stash
Flexible and rock solid audit log tracking for CakePHP 3
Stars: ✭ 66 (-7.04%)
Mutual labels:  cakephp

RestApi plugin for CakePHP 3

Build Status GitHub license Total Downloads Latest Stable Version

This plugin provides basic support for building REST API services in your CakePHP 3 application. Read a detailed guide on how to implement this here - CakePHP: Build REST APIs with RestApi plugin

Requirements

This plugin has the following requirements:

  • CakePHP 3.0.0 or greater.
  • PHP 5.4.16 or greater.

Installation

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

composer require multidots/cakephp-rest-api

After installation, Load the plugin

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

Or, you can load the plugin using the shell command

$ bin/cake plugin load -b RestApi

Usage

You just need to create your API related controller and extend it to ApiController instead of default AppController. You just need to set you results in apiResponse variable and your response code in httpStatusCode variable. For example,

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

You can define your logic in your action function as per your need. For above example, you will get following response in json format,

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

The URL for above example will be http://yourdomain.com/foo/bar. You can customize it by setting the routes in APP/config/routes.php.

Simple :)

Configurations

This plugin provides several configuration related to Response Format, CORS , Request Logging and JWT authentication. The default configurations are as below and defined in 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%[email protected]&s4Kf6*sd(5dHs!5gD4s',
            'tokenAlgorithm' => 'HS256'
        ],
        'cors' => [
            'enabled' => true,
            'origin' => '*',
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];

Debug

Set debug to true in your development environment to get original exception messages in response.

Response format

It supports json and xml formats. The default response format is json. Set responseType to change your response format. In case of xml format, you can set the root element name by xmlResponseRootNode parameter.

Request authentication using JWT

You can check for presence of auth token in API request. By default it is enabled. You need to define a flag allowWithoutToken to true or false. For example,

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

Above API method will require auth token in request. You can pass the auth token in either header, in GET parameter or in POST field.

If you want to pass token in header, use below format.

Authorization: Bearer [token]

In case of GET or POST parameter, pass the token in token parameter.

Generate jwt token

This plugin provides Utility class to generate jwt token and sign with same key and algorithm. Use JwtToken::generate() method wherever required. Most probably, you will need this in user login and register API. See below example,

<?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

By default, cors requests are enabled and allowed from all domains. You can overwrite these settings by creating config file at APP/config/api.php. The content of file will look like,

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

To disable cors request, set enabled flag to false. To allow requests from specific domains, set them in origin option like,

<?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
        ]
    ]
];

Log request & response

By default, request log is disabled. You can overwrite this by creating/updating config file at APP/config/api.php . The content of file will look like,

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

After enabling the log, you need to create a table in your database. Below is the table structure.

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;

Or you can use the bake command to automatically generate the above table.

$ bin/cake migrations migrate --plugin RestApi

Log only error responses

Sometimes, it is not necessary to log each and every request and response. We just want to log the request and response in case of error only. For that, you can set the additional settings using logOnlyErrors option.

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

If the logOnlyErrors is set, this will only log the request and response which are not equals to 200 OK. You can specify to log the request for only specific response code. You can specify the response codes in logOnlyErrorCodes option in array format. This will only work if the log option is set to true

Response format

The default response format of API is json and its structure is defined as below.

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

If you have set httpResponseCode to any value other that 200, the status value will be NOK otherwise OK. In case of exceptions, it will be handled automatically and set the appropriate status code.

You can modify the default response configuration like the text for OK response, key for main response data, etc. by overwriting them in your APP/config/api.php file.

In case of xml format, the response structure will look like,

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

Examples

Below are few examples to understand how this plugin works.

Retrieve articles

Let's create an API which returns a list of articles with basic details like id and title. Our controller will look like,

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

The response of above API call will look like,

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

Exception handling

This plugin will handle the exceptions being thrown from your action. For example, if you API method only allows POST method and someone makes a GET request, it will generate NOK response with proper HTTP response code. For example,

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

The response will look like,

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

Another example of throwing an exception,

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

And the response will be,

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

Reporting Issues

If you have a problem with this plugin or any bug, please open an issue on GitHub.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].