33
44This listener allows you to easily create a JSON or XML Api built on top of Crud.
55
6- Introduction
7- ------------
8- .. note ::
9-
10- The ``API listener `` depends on the ``RequestHandler `` to be loaded **before ** ``Crud ``.
11-
12- `Please also see the CakePHP documentation on JSON and XML views <http://book.cakephp.org/5/en/views/json-and-xml-views.html >`_
13-
146Setup
157-----
168
@@ -47,7 +39,6 @@ Attach it using components array, this is recommended if you want to attach it t
4739
4840 public function initialize(): void
4941 {
50- $this->loadComponent('RequestHandler');
5142 $this->loadComponent('Crud.Crud', [
5243 'actions' => [
5344 'Crud.Index',
@@ -60,21 +51,9 @@ Attach it using components array, this is recommended if you want to attach it t
6051 Request detectors
6152-----------------
6253
63- The Api Listener creates 3 new detectors in your ``Request `` object.
64-
65- is('json')
66- ^^^^^^^^^^
67-
68- Checks if the extension of the request is ``.json `` or if the requester accepts json as part of the
69- ``HTTP accepts `` header.
70-
71- is('xml')
72- ^^^^^^^^^
73-
74- Checks if the extension of the request is ``.xml `` or if the requester accepts XML as part of the ``HTTP accepts ``
75- header.
54+ The Api Listener will add a new `api ` detector to your ``ServerRequest `` class.
7655
77- is('api')
56+ ServerRequest:: is('api')
7857^^^^^^^^^
7958
8059Checking if the request is either ``is('json') `` or ``is('xml') ``.
@@ -94,18 +73,32 @@ In case of an error, in order to get a standardized response in either
9473``json `` or ``xml `` - according to the API request type, for `api ` requests,
9574the default CakePHP exception renderer needs to be overridden.
9675
97- Set the ``Error. exceptionRenderer `` config in `` config/app.php `` to
98- ``\Crud\Error\ExceptionRenderer::class `` as following:
76+ Set the ``exceptionRenderer `` config for the `` ErrorHandlerMiddleware `` in your
77+ ``Application::middleware() `` method in `` src/Application.php ``.
9978
10079.. code-block :: php
10180
102- 'Error' => [
103- 'errorLevel' => E_ALL,
104- 'exceptionRenderer' => \Crud\Error\ExceptionRenderer::class,
105- 'skipLog' => [],
106- 'log' => true,
107- 'trace' => true,
108- ],
81+ $middlewareQueue->add(
82+ new ErrorHandlerMiddleware(['exceptionRenderer' => \Crud\Error\ExceptionRenderer::class] + Configure::read('Error'), $this)
83+ )
84+
85+ You also need to update your ``ErrorController `` to use the ``JsonView `` or ``XmlView ``
86+ classes for content negotiation.
87+
88+ .. code-block :: php
89+
90+ // src/Controller/ErrorController.php
91+
92+ use Crud\View\JsonView;
93+ use Crud\View\XmlView;
94+
95+ public function initialize(): void
96+ {
97+ $this->addViewClasses([
98+ 'json' => JsonView::class,
99+ 'xml' => XmlView::class,
100+ ]);
101+ }
109102
110103 Request type enforcing
111104----------------------
0 commit comments