1. Go to this page and download the library: Download nilportugues/api-problems library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
nilportugues / api-problems example snippets
use NilPortugues\Api\Problem\ApiProblemResponse;
$additionalDetails = []; //you may pass additional details too.
/**@var $response is a PSR7 response */
$response = ApiProblemResponse::json(404,'User with id 5 not found.', 'Not Found', 'user.not_found', $additionalDetails);
$response = ApiProblemResponse::xml(404,'User with id 5 not found.', 'Not Found', 'user.not_found', $additionalDetails);
$response = ApiProblemResponse::fromExceptionToJson($exception);
$response = ApiProblemResponse::fromExceptionToXml($exception);
use NilPortugues\Api\Problem\ApiProblem;
use NilPortugues\Api\Problem\ApiProblemResponse;
use NilPortugues\Api\Problem\Presenter\JsonPresenter;
$apiProblem = new ApiProblem(
404,
'User with id 5 not found.',
'Not Found',
'user.not_found'
);
$presenter = new JsonPresenter($apiProblem); //or XmlPresenter
return new ApiProblemResponse($presenter);
use NilPortugues\Api\Problem\ApiProblem;
use NilPortugues\Api\Problem\ApiProblemResponse;
use NilPortugues\Api\Problem\Presenter\JsonPresenter;
try {
//...your code throwing an exception
throw new \Exception('User with id 5 not found.', 404);
} catch(\Exception $exception) {
$problem = ApiProblem::fromException($exception);
$presenter = new JsonPresenter($apiProblem); //or XmlPresenter
return new ApiProblemResponse($presenter);
}
use NilPortugues\Api\Problem\ApiProblem;
use NilPortugues\Api\Problem\ApiProblemResponse;
use NilPortugues\Api\Problem\Presenter\JsonPresenter;
try {
// some code of yours throws an exception... for instance:
throw new \Exception('User data is not valid.', 500);
} catch(\Exception $exception) {
$additionalDetails = [
'errors' => [
['name' => 'username', 'error' => 'Username must be at least 5 characters long.'],
['name' => 'email', 'error' => 'Provided address is not a valid email.'],
],
]
$apiProblem = ApiProblem::fromException(
$exception,
'Input values do not match the
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.