PHPackages                             pedrosalpr/laravel-api-problem - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. pedrosalpr/laravel-api-problem

ActiveLibrary[API Development](/categories/api)

pedrosalpr/laravel-api-problem
==============================

This is my package laravel-api-problem

0.0.4(7mo ago)92631[2 PRs](https://github.com/pedrosalpr/laravel-api-problem/pulls)MITPHPPHP ^8.1CI failing

Since Feb 10Pushed 7mo ago2 watchersCompare

[ Source](https://github.com/pedrosalpr/laravel-api-problem)[ Packagist](https://packagist.org/packages/pedrosalpr/laravel-api-problem)[ Docs](https://github.com/pedrosalpr/laravel-api-problem)[ GitHub Sponsors](https://github.com/pedrosalpr)[ RSS](/packages/pedrosalpr-laravel-api-problem/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (14)Versions (8)Used By (0)

Laravel Api Problem
===================

[](#laravel-api-problem)

[![Latest Version on Packagist](https://camo.githubusercontent.com/22f7da5d01d5b48973f264c05b802ed8656200661a89ce3b0e6ed04d4746a52a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f706564726f73616c70722f6c61726176656c2d6170692d70726f626c656d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pedrosalpr/laravel-api-problem)[![GitHub Tests Action Status](https://camo.githubusercontent.com/06b11a6cb813f0feb0c9a05aa088c1447df96964b8c5d868e1bf3b93868f02ce/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f706564726f73616c70722f6c61726176656c2d6170692d70726f626c656d2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/pedrosalpr/laravel-api-problem/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/face72fe622a471de0673b2b140bb683a0c30715ea9f0941f3474a7ca2a90011/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f706564726f73616c70722f6c61726176656c2d6170692d70726f626c656d2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/pedrosalpr/laravel-api-problem/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/ccbe71de5021efbb56e92725abff4b8e44442308ddd7ed0d358c3d848f212e0b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f706564726f73616c70722f6c61726176656c2d6170692d70726f626c656d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pedrosalpr/laravel-api-problem)

The objective of this package is to facilitate error outputs from API requests in accordance with the [RFC 9457](https://datatracker.ietf.org/doc/rfc9457/) standard.

It transforms error outputs into json format with the following characteristics:

- header:
    - `Content-Type: application/problem+json`
- response:
    - `type`: URI that identifies the type of error that occured, for example `https://example.com/validation-error`.
    - `title`: Human-readable identifier, usually the same type field should have the same title field alongside. An example would be something like Form validation failed.
    - `status`: A copy of the HTTP status code.
    - `detail`: More information about the specific problem, and if it's appropriate also steps to correct it. For example information about a form validation problem Username is already taken, please choose a different username.
    - `instance`: An identifier for this specific occurence, which may not be useful to the client but may be included in a bug report for example.
    - **Additional fields**: Any fields may be added to give additional information, and consuming clients are expected to ignore any that they don't have specific support for.
        - `timestamp`: (RFC 9457 enhancement): A timestamp indicating when the problem was generated. This helps in logging and tracing the error, especially in systems where timing is critical.

Example:

Server Response:

```
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
Content-Language: en
{
     "status": 422,
     "type": "https://example.test/validation-error",
     "title": "Form validation failed",
     "detail": "One or more fields have validation errors. Please check and try again.",
     "instance": "http://example.test/api/test/1",
     "timestamp": "2024-02-09T11:55:51.252968Z",
     "errors": [
        {
            "name": "username",
            "reason": "Username is already taken."
        },
        {
            "name": "email",
            "reason": "Email format is invalid."
        }
    ]
}
```

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require pedrosalpr/laravel-api-problem
```

Usage
-----

[](#usage)

### Default Mode (Older Version Laravel 9 and 10)

[](#default-mode-older-version-laravel-9-and-10)

To use it, just go to the `register` method within `Exceptions\Handler.php` and add the following code:

```
use Pedrosalpr\LaravelApiProblem\LaravelApiProblem;

public function register(): void
{
    ...

    $this->renderable(function (\Throwable $e, Request $request) {
        if ($request->is('api/*') || $this->shouldReturnJson($request, $e)) {
            $apiProblem = new LaravelApiProblem($e, $request);
            return $apiProblem->render();
        }
    });
}
```

If you want to debug, just add the following line before the return:

`dd($apiProblem->toDebuggableArray());`

### Default Mode (Laravel 11)

[](#default-mode-laravel-11)

To use it, add the following code to the Exception Closure in the `bootstrap/app.php` file:

```
use Pedrosalpr\LaravelApiProblem\LaravelApiProblem;

    ...

    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (\Throwable $e, Request $request) {
            if ($request->is('api/*') || $this->shouldReturnJson($request, $e)) {
                $apiProblem = new LaravelApiProblem($e, $request);
                return $apiProblem->render();
            }
        });
    })...
```

#### Creating Exceptions in the Api Problem pattern

[](#creating-exceptions-in-the-api-problem-pattern)

There is the possibility of creating exceptions that extend `LaravelApiProblemException`.

This already makes it easier to transform the exception into the Api Problem pattern.

To do this, simply run the following command:

`php artisan laravel-api-problem:exception {name}`

For example:

`php artisan laravel-api-problem:exception DummyException`

This creates a class exception inside `Exceptions\ApiProblem`;

```
