@@ -25,8 +25,76 @@ use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem;
25
25
return ApiProblem::response('Detailed Unauthorized Message', 401);
26
26
```
27
27
28
+ This will result in a 401 response with header
29
+
30
+ ``` shell
31
+ Content-Type: application/problem+json
32
+ ```
33
+
34
+ and content
35
+ ``` json
36
+ {
37
+ "type" : " http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" ,
38
+ "title" : " Unauthorized" ,
39
+ "status" : 401 ,
40
+ "detail" : " Detailed Unauthorized Messsge"
41
+ }
42
+ ```
43
+
44
+ ## Use
45
+
46
+ ### Using the facade
47
+
48
+ You may use the ApiProblem object in two ways. First, you can use the facade to
49
+ return a response quickly and directly as shown in the Quick Start. When using
50
+ the facade the arguments to the ` response() ` method are:
51
+
52
+ ``` php
53
+ response(string|Throwable $detail, int|string $status, ?string $type = null, ?string $title = null, array $additional = [])
54
+ ```
55
+
56
+ ### Creating an object
57
+
58
+ When creating an ApiProblem object directly, the first two parameters are swapped.
59
+ The reason for this is the constructor for the original object remains unchanged
60
+ and the ` response() ` function is modified to match the standard
61
+ [ Laravel response] ( https://laravel.com/docs/8.x/responses#response-objects )
62
+ format.
63
+
64
+ ``` php
65
+ __construct(int|string $status, string|Throwable $detail, ?string $type = null, ?string $title = null, array $additional = [])
66
+ ```
67
+
68
+ An example of creating an object directly:
69
+
70
+ ``` php
71
+ use ApiSkeletons\Laravel\ApiProblem\ApiProblem;
72
+
73
+ $apiProblem = new ApiProblem(401, 'Detailed Unauthorized Message');
74
+ return $apiProblem->response();
75
+ ```
76
+
77
+ ## Additional Details
78
+
79
+ The 5th parameter to ApiProblem is $additional. This array adds adhoc properties to the
80
+ JSON response. One method of using this array is a 422 response with details of the problem:
81
+
82
+ ``` php
83
+ use ApiSkeletons\Laravel\ApiProblem\Facades\ApiProblem;
84
+ use Illuminate\Validation\ValidationException;
85
+
86
+ try {
87
+ $validated = $request->validate([
88
+ 'title' => 'required|unique:posts|max:255',
89
+ 'body' => 'required',
90
+ ]);
91
+ } catch (\Illuminate\Validation\ValidationException $e) {
92
+ return ApiProblem::response($e->getMessage(), 422, null, null, ['errors' => $e->errors()]);
93
+ }
94
+ ```
95
+
28
96
## Attribution
29
97
30
98
The bulk of this repository was copied from Laminas API Tools. I wanted to provide a
31
99
simplified interface specific to Laravel. Though the tool could have been used directly
32
- from the Laminas library it would have come with a lot of overhead. Thanks Laminas.
100
+ from the Laminas library it would have come with a lot of overhead.
0 commit comments