infotechnohelp/cakephp-json-api_advanced

Plugin for CakePHP 3

dev-master 2019-07-28 07:50 UTC

This package is auto-updated.

Last update: 2024-04-28 18:46:23 UTC


README

Implementation

composer require infotechnohelp/cakephp-json-api_advanced

1. Add plugin

src/Application.php → bootstrap()

$this->addPlugin('Infotechnohelp/JsonApi', ['routes' => true]);

or use terminal

bin/cake plugin load Infotechnohelp/JsonApi -r

2. Set path prefixes

config/infotechnohelp.json-api.yml

pathPrefixes:
- api
- auth-api (automatically later)

If route contains /api/ string ('/' from both sides), request is treated as an API one.

You may add any required prefixes.

3. Set ErrorHandlerMiddleware (JSON response structure)

Replace manually in APP/src/Application.php

use Cake\Error\Middleware\ErrorHandlerMiddleware;use Infotechnohelp\JsonApi\Middleware\ErrorHandlerMiddleware;

Usage

API layer

Create Api Controller

Path: APP/src/Controller/Api

namespace App\Controller\Api;

use Infotechnohelp\JsonApi\Traits\ApiController;


class MyController extends AppContoller
{
    use ApiController;
    
    public function get()
    {
        $this->getRequest()->getQuery(); // GET data params
        $this->_setResponse([1, 2, 3]);
    }
	
	public function post()
    {
        $this->_getRequestData(); // POST data params
        $this->_setResponse([1, 2, 3]);
    }
}

Response structure

{ "data": {"1", "2", "3"}, "code": 200, message": null }

In case a message has a value (Exception message), data is null.

If data is null, but no Exception was thrown, a custom exception 'Data was not set' will be thrown.

Send requests

Prefix api/

In order to send request to APP/src/Controller/Api/MyController→get(), use this path:

api/my/get

In case you need to pass such values as null, true or false in a request body, you need to convert JS data object to JSON. API layer will automatically parse the request data.

I.E.

        // Values will be parsed as strings
        api.postJson("demo/create", {
            _true: true,
            _false: false,
            _null: null
        }, function (response) {
            log.single(response);
        });

        // Values will be parsed as booleans and NULL
        api.postJson("demo/create", JSON.stringify({
            _true: true,
            _false: false,
            _null: null
        }), function (response) {
            log.single(response);
        });

Allowed actions-methods pairs

index, view, read, get → GET

create, add, post → POST

update → POST, PUT

delete → POST, DELETE