Skip to content

Commit 1e1bf3b

Browse files
committed
readme updated
1 parent bed07be commit 1e1bf3b

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

README.md

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,67 @@
11
# JsonApiException plugin for CakePHP
22

3+
Make your CakePHP 4 JSON REST API response more descriptive on errors.
4+
5+
If you want a simple solution for token authentication for a CakePHP JSON REST API, then check this: [CakePHP API Token Authenticator](https://github.com/rrd108/api-token-authenticator)
6+
37
## Installation
48

59
You can install this plugin into your CakePHP application using [composer](https://getcomposer.org).
610

7-
The recommended way to install composer packages is:
11+
The recommended way to install is:
812

913
```
1014
composer require rrd108/cakephp-json-api-exception
1115
```
1216

17+
Then, to load the plugin either run the following command:
18+
1319
```
1420
bin/cake plugin load JsonApiException
1521
```
22+
23+
or manually add the following line to your app's `src/Application.php `file's `bootstrap()` function:
24+
25+
```php
26+
$this->addPlugin('JsonApiException');
27+
```
28+
29+
done :)
30+
31+
## How to use
32+
33+
Assuming you have a CakePHP JSON REST API and you want to have more informative error messages and proper response codes.
34+
35+
```php
36+
// for example in /src/Controller/UsersController.php slightly change the baked add function
37+
use JsonApiException\Error\Exception\JsonApiException;
38+
39+
public function add()
40+
{
41+
$user = $this->Users->newEmptyEntity();
42+
if ($this->request->is('post')) {
43+
$user = $this->Users->patchEntity($user, $this->request->getData());
44+
if (!$this->Users->save($user)) {
45+
throw new JsonApiException($user, 'Save failed');
46+
}
47+
}
48+
$this->set(compact('user'));
49+
$this->viewBuilder()->setOption('serialize', ['user']);
50+
}
51+
```
52+
53+
If the save failed you will get a response like this.
54+
55+
```json
56+
{
57+
"message": "Save failed",
58+
"url": "/users.json",
59+
"line": 12,
60+
"errorCount": 1,
61+
"errors": {
62+
"password": {
63+
"_required": "This field is required"
64+
}
65+
}
66+
}
67+
```

0 commit comments

Comments
 (0)