Errors
An API that answers its errors in a shape of its own makes every client learn that shape. The
package answers every failure of an API request as JSON:API error objects
(JSON:API 1.1, Errors), served as
application/vnd.api+json:
{
"errors": [
{
"status": "404",
"code": "not_found",
"title": "Not found",
"detail": "The requested resource does not exist.",
"meta": {
"request_id": "019a9c9e-4d39-74db-a2f5-b0c1d2e3f405"
}
}
]
}
Every status, code, title and detail comes from one error catalog that the package carries, a copy
of errors/codes.json, the file the Frontline gateway answers from. An error the gateway answers
and the same error from Laravel are the same response: the same status, the same headers and the
same bytes, apart from the request id.
Which requests get errors
A failure is answered with JSON:API errors when the request
- goes to the API host:
api.before the host ofapp.url, so an application atexample.comanswers its API atapi.example.com.HTTP_API_HOSTnames another host; - goes to a host in
http-api.errors.hosts, or under a prefix inhttp-api.errors.route_prefixes. The package ships no prefix; - asks for
application/vnd.api+jsonin itsAcceptheader.
Every other request is answered as Laravel answers it, so a page stays a page, and a request that
expects JSON outside the API keeps Laravel's JSON with its message. Setting
http-api.errors.when_json_is_expected to true answers such a request with JSON:API errors as
well, outside the API too.
An application that knows its API better, by a path or a middleware of its own, binds its own
RecognizesApiRequests. The class goes into app/Http/ApiRequests.php:
namespace App\Http;
use Illuminate\Http\Request;
use Pushery\HttpApi\Errors\RecognizesApiRequests;
final class ApiRequests implements RecognizesApiRequests
{
public function isApiRequest(Request $request): bool
{
return $request->is('v1', 'v1/*');
}
}
The binding goes into the register method of a service provider:
use App\Http\ApiRequests;
use Pushery\HttpApi\Errors\RecognizesApiRequests;
$this->app->bind(RecognizesApiRequests::class, ApiRequests::class);
The error object
| Member | Content |
|---|---|
status | the HTTP status, as a string |
code | stable, for programs: not_found, validation_failed |
title | short, the same for every error of the code |
detail | says what to do |
source | the input that caused the error: pointer for a member of the body, parameter for a query parameter, header for a header |
meta | request_id, the id of the request |
The members come in this order, without whitespace. The title and the detail are English and come
from the catalog, never from the message of an exception: abort(403, 'Exports are not part of this plan.') answers with the catalog's detail for forbidden, and the message of a missing model,
which names its class and its key, never reaches a client.
The response carries Content-Type: application/vnd.api+json, Cache-Control: no-store, private,
the request id in Request-Id, and the headers its code names, such as WWW-Authenticate: Bearer
for a 401. It carries no other header, with two exceptions: a throttled request keeps its limit
headers, and the maintenance mode keeps its Retry-After when the end is known.
Behind the gateway, the request id is the one the gateway assigned and sent along as
Frontline-Request-Id, so the client, the gateway's log and the application's error name the same
request. Without the gateway, each request gets a new UUID of version 7.
The codes
The codes Laravel answers with:
| Status | Code | Title | Answers |
|---|---|---|---|
| 400 | malformed_ | Malformed request | abort(400), a missing or malformed Idempotency-Key, a page parameter a list cannot take, and a filter, sort, include, field or append its route does not declare |
| 401 | unauthenticated | Unauthenticated | an AuthenticationException |
| 403 | forbidden | Forbidden | a refused authorization, and abort(403) |
| 404 | not_ | Not found | a missing route or model, and a known path asked with another method |
| 406 | not_ | Not acceptable | an Accept header that admits no JSON:API answer |
| 409 | conflict | Conflict | a request under an Idempotency-Key whose answer was not kept |
| 409 | request_ | Request in flight | a request under an Idempotency-Key whose first request still runs, with Retry-After |
| 412 | precondition_ | Precondition failed | abort(412) |
| 413 | payload_ | Payload too large | a body larger than PHP takes |
| 415 | unsupported_ | Unsupported media type | a body that is no JSON:API |
| 422 | validation_ | Validation failed | a failed validation, and an Idempotency-Key sent with another request |
| 428 | precondition_ | Precondition required | abort(428) |
| 429 | rate_ | Too many requests | the throttle middleware |
| 500 | internal_ | Internal error | every other failure, and a status the catalog has no code for |
| 503 | maintenance | Under maintenance | the maintenance mode |
The gateway answers further codes of its own, such as request_timeout and backend_unavailable.
The catalog in the package lists every one of them.
How a failure is answered
- A failed validation is one error per invalid field. A member of the body is named by its JSON
pointer: the field
data.attributes.titleis/data/attributes/title. A field the query carries and the body does not is named by its parameter,filter[status], and so is every field of aGET. Laravel's message for the field does not reach the client: the detail ofvalidation_failedtells it to readsource. - A missing route, a missing model and a known path asked with another method answer the same
404. A405would list the methods of a path to anyone who asks, and the gateway in front never answers one. - A throttled request names its wait in
Retry-Afterand in the detail. - An exception nobody anticipated answers
500internal_error, and it reaches the reporters like every other. Withapp.debugon, Laravel's debug answer stays, which is what a developer wants to read. - An exception that carries its own response, an
HttpResponseExceptionor a validation given one, keeps that response.
Content negotiation
NegotiateJsonApi holds a route to the content negotiation of JSON:API 1.1. It goes on the routes
that speak JSON:API, in routes/api.php:
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;
use Pushery\HttpApi\Errors\NegotiateJsonApi;
Route::post('/articles', [ArticleController::class, 'store'])
->middleware(['auth:sanctum', NegotiateJsonApi::class]);
A request body comes as application/vnd.api+json. One in another media type, one with a media type
parameter other than profile, and one that asks for an extension through ext is refused with
415 unsupported_media_type, because the package supports no extension. An Accept header that
admits no JSON:API answer is refused with 406 not_acceptable: it names the media type, and every
time with another parameter or with an extension, or it names neither the media type nor a range
that covers it. A request without Accept takes any answer.
An error of your own
An exception that implements ProvidesErrorDocument answers with the errors it names, made from the
catalog with JsonApiError::of(), so a code the catalog does not have cannot be answered. The class
goes into app/Exceptions/OutOfStock.php:
namespace App\Exceptions;
use Pushery\HttpApi\Errors\ErrorDocument;
use Pushery\HttpApi\Errors\JsonApiError;
use Pushery\HttpApi\Errors\ProvidesErrorDocument;
use RuntimeException;
final class OutOfStock extends RuntimeException implements ProvidesErrorDocument
{
public function toErrorDocument(): ErrorDocument
{
return ErrorDocument::of(JsonApiError::of('conflict', source: ['pointer' => '/data/attributes/quantity']));
}
}
A code with more than one detail takes the name of the detail to answer with, and the values of its
placeholders: JsonApiError::of('rate_limited', 'key', ['limit' => '120', 'window' => 'minute', 'retry_after' => '12']) answers "This key is limited to 120 requests per minute. Retry after 12
seconds."
Switching it off
HTTP_API_ERRORS=false leaves every failure to Laravel, and HTTP_API_ENABLED=false switches the
whole package off. With the errors alone switched off, the idempotency middleware still answers its
refusals as JSON:API errors.
Upgrading from 0.3
- Configuration: the section
problemsiserrors.type_baseandwww_authenticateare gone, andwhen_json_is_expectedshipsfalse.HTTP_API_PROBLEMSisHTTP_API_ERRORS, andHTTP_API_PROBLEM_TYPE_BASEis gone. A publishedconfig/http-api.phpis published again or edited by hand. - Classes:
ProvidesProblemisProvidesErrorDocument, which returns anErrorDocumentof errors made from the catalog.Problem,ProblemRenderer,NamesProblemsandCatalogLanguageare gone, because the catalog decides every code, title and detail.RecognizesApiRequestsandConfiguredApiRequestsmoved toPushery\HttpApi\Errors. - Translations: the package ships no catalogs, and the tag
http-api-langpublishes nothing. The translations an application published for the package can go. - Clients: an error is
{"errors": [...]}inapplication/vnd.api+json, and a client branches oncodeinstead oftype. A refused idempotency key answers with its code and names the header insource.header, and a key the store does not take answers500internal_errorinstead of503.